Git Product home page Git Product logo

Comments (17)

seandevenish avatar seandevenish commented on June 5, 2024 12

In case anyone else runs into this, I started with disabling 'initialNavigation' per the above comments.

export const routing = RouterModule.forRoot(routes, {
    initialNavigation: false // <- turn off the initial redirect, used for redirect or hash routing strategy
});

Then, I found the best approach is to trigger the router navigation immediately after the login attempt using the following (which also implements passing the state parameter).

this.oauthService.loadDiscoveryDocumentAndTryLogin({
      onTokenReceived: (info) => {
        if (info.state) this.router.navigate([info.state]);
      }
    }).then(
      info => this.router.initialNavigation()
    );

from angular-oauth2-oidc.

ropstah avatar ropstah commented on June 5, 2024 3

I think the problem is related to when it is the '' (root) route being matched (or at least on the first load for the UI) where regular implementations call the asynchronous loadDiscoveryDocumentAndTryLogin() method in some AppComponent constructor. The Angular request lifecycle gets at the GuardsCheck* events before the discovery document is returned and the TryLogin part can be executed.

Besides bedag-moo's comment (I wasn't able to call execute the TryLogin() method in the CanActivatemethod) you can return anObservable` in the guard like so:

canActivate(): Observable<boolean> {
  return fromPromise(this.auth.loadDiscoveryDocumentAndTryLogin()).map(() => {

    if(this.auth.hasValidIdToken()) { //or AccessToken
      console.log('authenticated');
      return true;
    }

    console.log('not authenticated');
    this.auth.initImplicitFlow();

    return false;
  });
}

from angular-oauth2-oidc.

yingding avatar yingding commented on June 5, 2024 2

Try to output your routes with

export const routing = RouterModule.forRoot(routes, {
    useHash: true,
    enableTracing: true, // <- debug the routes
    initialNavigation: false // <- turn off the initial redirect, used for redirect or hash routing strategy
});

I have got the same effect to have an own login service that wrappes the oauthservice, but it turned out i got a loop in routes definition wth the canActivate method. Thus, tryLogin() was never executed in app.component.ts.

Double check your _storage (sessionStorage/localStorage) to see if there are tokens stored or exist. If oidc is used and id token shall be provided, also double check that the issuer is provided. If the id token doesn't pass the issuer check, the access token will not be passed either.

@manfredsteyer: this library is the most best third-part angular2 lib i can found. I can confirm it works very well with google open id connect and oauth2 while using angular 2.4.10 and hashLocation strategy.

from angular-oauth2-oidc.

mraible avatar mraible commented on June 5, 2024 1

Here's what I've used successfully:

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { OAuthService } from 'angular-oauth2-oidc';

@Injectable()
export class AuthGuard implements CanActivate {

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

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (this.oauthService.hasValidIdToken()) {
      return true;
    }

    this.router.navigate(['/home']);
    return false;
  }
}

from angular-oauth2-oidc.

Gimly avatar Gimly commented on June 5, 2024 1

I have a very similar issue (#76) as you describe, what ended up being wrong for me what the redirectUrl. For some reason, it didn't work with just using this.oAuthService.redirectUri = window.location.origin;, I had to concatenate index.html to the end of the location origin: this.oAuthService.redirectUri = window.location.origin + '/index.html';.

Hope this helps.

from angular-oauth2-oidc.

mtttcgcg avatar mtttcgcg commented on June 5, 2024 1

Had similar issue. Thanks to yingding's answer above, all I needed was export const routing = RouterModule.forRoot(routes, {
initialNavigation: false // <- turn off the initial redirect, used for redirect or hash routing strategy
});

from angular-oauth2-oidc.

bedag-moo avatar bedag-moo commented on June 5, 2024

You are invoking oauthService.tryLogin({}), aren't you? (see Readme for more info)

from angular-oauth2-oidc.

CrescentFresh avatar CrescentFresh commented on June 5, 2024

Same problem. Yes we are calling tryLogin() inside the loadDiscoveryDocument() resolve step.

However guards for the route seem to be invoked before tryLogin gets a chance to capture the auth tokens from the url. forever redirecting back to home.

from angular-oauth2-oidc.

CrescentFresh avatar CrescentFresh commented on June 5, 2024

@Gimly: I don't think that's related at all.

from angular-oauth2-oidc.

Gimly avatar Gimly commented on June 5, 2024

@CrescentFresh The symptoms were similar, that's why I said that.

from angular-oauth2-oidc.

manfredsteyer avatar manfredsteyer commented on June 5, 2024

How does your redirect url look like (including params?)

from angular-oauth2-oidc.

manfredsteyer avatar manfredsteyer commented on June 5, 2024

thanks @yingding

from angular-oauth2-oidc.

rmathieson avatar rmathieson commented on June 5, 2024

In case anyone else runs into this, I started with disabling 'initialNavigation' per the above comments.

export const routing = RouterModule.forRoot(routes, {
    initialNavigation: false // <- turn off the initial redirect, used for redirect or hash routing strategy
});

Then, I found the best approach is to trigger the router navigation immediately after the login attempt using the following (which also implements passing the state parameter).

this.oauthService.loadDiscoveryDocumentAndTryLogin({
      onTokenReceived: (info) => {
        if (info.state) this.router.navigate([info.state]);
      }
    }).then(
      info => this.router.initialNavigation()
    );

This worked for me also, thanks @seandevenish

from angular-oauth2-oidc.

ganeshchippada avatar ganeshchippada commented on June 5, 2024

@seandevenish Thanks for the suggestion. you saved my time :)

from angular-oauth2-oidc.

NDIAYE-baoussou avatar NDIAYE-baoussou commented on June 5, 2024

Then, I found the best approach is to trigger the router navigation immediately after the login attempt using the following (which also implements passing the state parameter).

this.oauthService.loadDiscoveryDocumentAndTryLogin({
      onTokenReceived: (info) => {
        if (info.state) this.router.navigate([info.state]);
      }
    }).then(
      info => this.router.initialNavigation()
    );

@seandevenish can you please tell me where you put this part in your code ?

I have same issue.

this my authgard authentification code :

 canActivate(
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
      if (this.authService.hasValidIdToken()) 
      //if (this.authService.isUserLoggedIn()) 
      {
          return true;
      }
      return false;
      
  }

And then i put your code in my app.component.ts :

this.oauthService.loadDiscoveryDocumentAndTryLogin({
onTokenReceived: (info) => {
if (info.state) this.router.navigate([info.state]);
}
}).then(
info => this.router.initialNavigation()
);

Could someone please tell me if he was able to get Authguard to work with this package (angular-oauth2-oidc
) while using the hashlocation strategie ({useHash: true, initialNavigation: "disabled"}) ?

from angular-oauth2-oidc.

seandevenish avatar seandevenish commented on June 5, 2024

@NDIAYE-baoussou The code is placed in a service, the method of which is called in the root app.component.ts in the ngOnInit() call.

Auth guard looks like this:

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {

    if (this.authService.loggedIn) {
      return true;
    }

    this.oauthService.initCodeFlow(state.url);
  }

I am pretty sure this approach works with and without the hashlocation strategy, though haven't had time to check.

from angular-oauth2-oidc.

NDIAYE-baoussou avatar NDIAYE-baoussou commented on June 5, 2024

@seandevenish thank you for your feedback. I'll test your method. I thought of a problem that could arise: how to redirect the user in not allowed page if he does not have the right to access in my app (invalid id token or access token) ?

from angular-oauth2-oidc.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.