Search code examples
angulartypescriptjwttokenauth0

Typescript, Angular4: array goes empty after refreshing browser


I have problem with an array which is used for storing roles in authorization service in angular app. I am using auth0 service to logging in. The auth.service.ts looks like this:

  @Injectable()
export class AuthService {
  userProfile: any;
  private roles: string[] = [];
 ...
  public handleAuthentication(): void {
this.auth0.parseHash((err, authResult) => {
  if (authResult && authResult.accessToken && authResult.idToken) {
    window.location.hash = '';
    this.setSession(authResult);
    this.getRoles(authResult);
    this.router.navigate(['/']);
  } else if (err) {
    this.router.navigate(['/']);
    console.log(err);
    alert(`Error: ${err.error}. Check the console for further details.`);
  }
});}
//THIS IS getRole function
private getRoles(authResult){
let jwtHelper = new JwtHelper();
let decodedToken = jwtHelper.decodeToken(authResult.idToken);
this.roles = decodedToken['https://tobenorme.com/roles'];

}

After login handleAuthentication function is invoked and everything work fine until refresh button is clicked. Then array of roles returns empty array and I am no longer able to get roles. I tried store them in local storage but it can be edited in the browser.


Solution

  • Since stated using JWT tokens (https://auth0.com/docs/jwt) you can securely rely on storing the tokens in local storage or cookies. JWT tokens are signed so every local change in the browser will be detected on the server while decrypting the token with every API call.

    Local changes can't be avoided, however the server side should always ensure that a user actually has the provided roles/rights.

    You can consult the following example: https://github.com/auth0/angular2-jwt