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.

Tokens are not set immediately after redirect

See original GitHub issue

Hello,

I am using version 3.1.4 of this library. My set-up is as follows:
after users enters his credentials on the identity server he is redirected to a protected resource.
My canActivate method looks as follows.

canActivate(): boolean {
    const validIdToken = this.oauthService.hasValidIdToken;
    const validAccessToken = this.oauthService.hasValidAccessToken();
    return (validIdToken && validAccessToken);
  }

However, at the time when canActivate() is called both tokens are not available immediately
(even though user is authenticated and they should be set).
canActivate() also returns false. I can see they eventually arrive:

this.oauthService.events.subscribe(({ type } : OAuthEvent) => {
      switch (type) {
        case 'token_received':
          const idToken = this.oauthService.getIdToken();
          const accessToken = this.oauthService.getAccessToken();
          if (accessToken && idToken) {
            console.log(accessToken);
            console.log(idToken);
          }
      }
 });

Is there some way to prevent this - ensuring that they are already set when canActivate() is called?

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:2
  • Comments:16 (5 by maintainers)

github_iconTop GitHub Comments

3reactions
meron1122commented, Feb 14, 2018

@Razzeee In my app, on routing i use CanActivate - which secure access to component before you are not login ( You are not logged - component cannot be load, first login bro!)

My app.component.ts

export class AppComponent {

    constructor(private oauthService: OAuthService) {
        this.oauthService.configure(authConfig);
        // this.oauthService.setStorage(localStorage);
        this.oauthService.tokenValidationHandler = new JwksValidationHandler();
        this.oauthService.setupAutomaticSilentRefresh();

        this.oauthService.loadDiscoveryDocumentAndLogin();
    }


Routing:


export const routes: Routes = [
    {
        path: '',
        redirectTo: 'dashboard',
        pathMatch: 'full'
    },
    {
        path: '',
        canActivate: [AuthGuard], //guard secure acces
        component: FullLayoutComponent,
        data: {
            title: 'Home'
        },
        children: [
            {
                path: 'dashboard',
                loadChildren: './dashboard/dashboard.module#DashboardModule'
            },
            {
                path: 'UsersList',
                loadChildren: './users/users-list/users-list.module#UsersListModule'
            },
            // ,
            // { path: '**', redirectTo: 'dashboard' }
        ],
    },
    // { path: '**', redirectTo: 'dashboard' },
];

And finally guard


@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private oauthService: OAuthService, private router: Router) {}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
        return this.oauthService
            .loadDiscoveryDocumentAndTryLogin()
            .then((res) => {
                return this.oauthService.hasValidIdToken() && this.oauthService.hasValidAccessToken()
            });
    }
}
3reactions
EricWaffordcommented, Feb 6, 2018

you’ll need to resolve the above event that you demonstrate subscribing to within your guard because you must wait for the discovery document to load, which is async. canActivate can accept a promise return, or better yet an Observable<boolean>. One option might be to use the OAuthService.TryLogin() which returns a promise, something like:

return this.oauthService
      .tryLogin()
      .then(() => { this.oauthService.hasValidIdToken() && this.oauthService.hasValidAccessToken() }

*The above is pseudo-code, your implementation will most likely vary. HTH

Read more comments on GitHub >

github_iconTop Results From Across the Web

Grabbing the OAuth Token From URL After Redirect URI ...
Any idea how can I achieve the same with useHash set to true since keycloak doesn't allow # in the redirect_uri? – Junaid....
Read more >
OAuth redirect after getting access token - the Tyk community
I am not speaking about redirect to login page that is working fine. I am talking about after reaching login, then getting authorisation...
Read more >
Redirect URL Validation - OAuth 2.0 Simplified
If the redirect URL is not one of the registered redirect URLs, then the server must immediately show an error indicating such, and...
Read more >
Stealing OAuth Tokens With Open Redirects - Okta Security
For example, if you are logged into “facebook.com”, you won't have to ... Some sites will redirect to the Referer automatically after ......
Read more >
Redirect Users - Auth0
Describes how to redirect users to URLs that have not been added to the AllowList. ... your application after validating their ID Tokens...
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