Keycloak Angular 2 - Check authenticated status Keycloak object
<p>I'm implementing the Keycloak authentication service in my Angular 2 project. 
I use a service for logging in, logging out etc. </p>

<p>Authenticating a user and logging out seems to work. I'm now trying to protect some routes. I now have a working AuthGuard. 
To check if the user is logged in (in the AuthGuard), I have a isAuthenticated() method in the service. 
This is the service: </p>

<pre><code>import { Injectable } from '@angular/core';

declare let Keycloak: any;

@Injectable()
export class KeycloakService {
  private keycloak = new Keycloak('app/keycloak/keycloak.json');

  constructor() {
    this.keycloak.init({onload: 'check-sso'});
    console.log(this.keycloak);
  }

  public login() {
    this.keycloak.login();
  }

  public logout() {
    this.keycloak.logout();
  }

  public isAuthenticated() {
    return this.keycloak.authenticated;
  }
}
</code></pre>

<p>Flow: User logs in, user tries to reach protected route, AuthGuard checks if user is logged in via isAuthenticated(). </p>

<p><em>Note:</em> I don't want to authenticate the user for the complete Angular app. Only for some routes. </p>

<p><strong>Problem</strong></p>

<p>After the user logs in, the user is redirected to the Angular app. After this, the isAuthenticated() method returns  still false. Here is why:</p>

<p>I logged the Keycloak object to the console. I found something I didn't understand. </p>

<p><a href="https://i.stack.imgur.com/cQGlD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cQGlD.png" alt="Keycloak object after login redirect"></a></p>

<p>Keycloak object after login redirect</p>

<hr>

<p><a href="https://i.stack.imgur.com/VfdZU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VfdZU.png" alt="Same Keycloak object after login redirect (but expanded)"></a></p>

<p>Same Keycloak object after login redirect (but expanded)</p>

<p>First the authenticated property is false. After expanding the authenticated property is true. </p>

<p><strong>Question</strong></p>

<p>Is the way I try to maintain my Keycloak object the correct way?</p>

<p><strong>Consulted sources</strong></p>

<ul>
<li><a href="https://keycloak.gitbooks.io/securing-client-applications-guide/content/v/2.5/topics/oidc/javascript-adapter.html" rel="noreferrer">https://keycloak.gitbooks.io/securing-client-applications-guide/content/v/2.5/topics/oidc/javascript-adapter.html</a></li>
<li><a href="https://github.com/keycloak/keycloak/tree/master/examples/demo-template/angular2-product-app/src/main/webapp/app" rel="noreferrer">https://github.com/keycloak/keycloak/tree/master/examples/demo-template/angular2-product-app/src/main/webapp/app</a></li>
</ul>

<p>And others</p>