1

I'm on a angular project using angular-oauth2-oidc. There is login component, a home component and a auth guard that enable to go to /home only if I'am connected. The connection is with google sign in oauth2.

When I try to use canActivate on the /home it always returns false. I am doing an implicit flow and when it redirects back it seems like it does not wait for the service to be aware of the login and it always redirects back to the login page.

the Guard for the route seems to be invoked before tryLogin gets a chance to capture the auth tokens from the url. forever redirecting back to login.

that's the code :

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(['/login']);
        return false;
    }
}

export class AppComponent {

    constructor(public oauthService: OAuthService) {
        this.configureOAuth();
    }
    private configureOAuth() {
        this.oauthService.configure({
            clientId: 'XXXX.apps.googleusercontent.com',
            issuer: 'https://accounts.google.com',
            redirectUri: 'http://localhost:4000/home',
            scope: 'openid profile email',
            showDebugInformation: true,
            strictDiscoveryDocumentValidation: false, 
            tokenEndpoint: 'https://oauth2.googleapis.com/token',
            loginUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
            jwks: {
                url: 'https://www.googleapis.com/oauth2/v3/certs'
            }
        });
        this.oauthService.loadDiscoveryDocumentAndTryLogin();
    }
}

export class LoginComponent implements OnInit {

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

    ngOnInit() {
        //Check if already connected
        if (this.oauthService.hasValidAccessToken()) {
            this.router.navigate(['/home']);
        }
    }

    login() {
        this.oauthService.initImplicitFlow();
    }

}

const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'login', component: LoginComponent },
  { path: 'home', component: HomeComponent, canActivate: [AuthGuard]}
]

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
Lucas
  • 11
  • 1

0 Answers0