question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unable to get name or other properties from Json Web Token after authentication

See original GitHub issue

Issue type

I’m submitting a … (check one with “x”)

  • code issue
  • feature request

Issue description

Current behavior: After a successful authentication with Azure AD B2C and redirect back to the dashboard, the header.component and a custom component I’ve built, which is injected with the user.service (which has code to update the user object on token change), isn’t displaying any of the information in the token payload, such as the user’s name.

image

Steps to reproduce: My user.service.ts code is here:

import { Observable } from 'rxjs';
import { of } from 'rxjs/observable/of';
import { Injectable } from '@angular/core';

import { NbAuthOAuth2Token, NbAuthService } from '@nebular/auth';

@Injectable()
export class UserService {

  user = {
    name: 'JJGriff93',
    given_name: 'James',
    family_name: 'Griffin',
    rank: 'PD Foundation 1',
    level: 1,
    totalXP: 704,
    toNextLvl: 296,
    picture: 'assets/images/defaultThumbnail.png',
    leaderboardPosition: 1,
  };

  constructor(private authService: NbAuthService) {
    this.authService.onTokenChange()
      .subscribe((token: NbAuthOAuth2Token) => {

      if (token.isValid()) {
        this.user = token.getPayload(); // receive payload from token and assign it to our `user` variable
      }

    });
  }

  getUser(): Observable<any> {
    return of(this.user);
  }

  // Add in assigning of token values to user properties
}

And an example of how it’s injected into the header.component:

import { Component, Input, OnInit } from '@angular/core';

import { NbMenuService, NbSidebarService } from '@nebular/theme';
import { UserService } from '../../../@core/data/users.service';
import { AppMonitoringService } from '../../../@core/monitoring/app-monitoring.service';

@Component({
  selector: 'ngx-header',
  styleUrls: ['./header.component.scss'],
  templateUrl: './header.component.html',
})
export class HeaderComponent implements OnInit {

  @Input() position = 'normal';

  user = {};

  userMenu = [{ title: 'Profile' }, { title: 'Log out' }];

  constructor(private sidebarService: NbSidebarService,
              private menuService: NbMenuService,
              private userService: UserService,
              private appMonitoringService: AppMonitoringService) { }

  ngOnInit() {
    this.user = this.userService.user;
  }

  toggleSidebar(): boolean {
    this.sidebarService.toggle(true, 'menu-sidebar');
    return false;
  }

  toggleSettings(): boolean {
    this.sidebarService.toggle(false, 'settings-sidebar');
    return false;
  }

  goToHome() {
    this.menuService.navigateHome();
  }

  startSearch() {
    this.appMonitoringService.logEvent('startSearch');
  }

I’ve double checked the JWT in a decoder and it has the name, given_name and family_name properties, so not sure why Nebular is unable to find these

May be a problem with how I’m injecting it, any advice would be really appreciated

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:9 (4 by maintainers)

github_iconTop GitHub Comments

2reactions
alain-charlescommented, Sep 14, 2018

@jjgriff93 ` I did not try it, but If you want your component to observe the user attribute you declared in your user service, you could try to

  • in userService, declare the user attribute as a BehaviorSubject, something like this :
protected user$: BehaviorSubject<any> = new BehaviorSubject(null);
  • in userService create a publishUser(user: any) method with something like
private publishUser(user: any) {
   this.user$.next(user)
}
  • in userService create a onUserChange() method with something like this :
  onUserChange(): Observable<any> {
    return this.user$;
}
  • in userService constructor, modify your subscription to NbAuthService.onTokenChange(), with something like this :
    this.authService.onTokenChange()
      .subscribe((token: NbAuthAzureToken) => {

      if (token.isValid()) {
        this.publishUser (token.getAccessTokenPayload()); // receive payload from token and assign it to our `user` variable
      }

    });
  • at last, in your component, subscribe to userService.onUserChange() with something like this
 ngOnInit() {
    this.userService.onUserChange()
      .subscribe((user: any) => this.user = user);
  }
1reaction
alain-charlescommented, Sep 12, 2018

And moreover, in the code above, you have to call getAccessTokenPayload() instead of getPayload() :

this.authService.onTokenChange()
      .subscribe((token: NbAuthOAuth2JWTToken) => {
      if (token.isValid()) {
        this.user = token.getAccessTokenPayload(); 
      }
    });

Before that do not forget to declare NbAuthOAuth2JWTToken class instead of NbAuthOAuth2Token in your auth strategy

Read more comments on GitHub >

github_iconTop Results From Across the Web

Unable to access additional data with token in Web api 2 ...
If you're using JWT (JSON Web Tokens) you can view the contents of the generated token at https://jwt.io/ Just paste your token into...
Read more >
How to get an access token with JWT Grant
Demonstrates how to get an access token using JSON Web Token (JWT) Grant authentication.
Read more >
Troubleshooting JWT validation
Check that the "iss" (issuer) claim in your JWT token matches the first parameter of the endpoints.Issuer object. Error: Audience not allowed. If...
Read more >
JWT authentication: Best practices and when to use it
Learn how to best use JWT to trust requests by using signatures, exchanging information between parties, and preventing basic security ...
Read more >
JWT: The Complete Guide to JSON Web Tokens
This post is the first part of a two-parts step-by-step guide for implementing JWT-based Authentication in an Angular application (also ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found