Hello, posting here after migrating from Auth0.js to Auth0-spa.js. Everything seems to work fine except there seems to be some kind of race condition when calling handleAuthCallback and having an AuthGuard as suggested in the migration docs and Angular setup docs.
I have lazy-loaded routes/modules. With the App Module splitting auth and home. My redirect_uri is /home/dashboard. I have tried calling handleAuthCallback from AppComponent, my Dashboard component (which the user gets redirected to after login), and the constructor of the AuthService. The most success I’ve seen is AppComponent and adding a delay(500) RxJs Operator to the authComplete$ code. Obviously, that’s a hack and not ideal. Also, I removed the combineLatest part with fetching the UserProfile because I don’t need that information. Although, I tried it initially with it there and the same issue still occurred.
const authComplete$ = this.handleRedirectCallback$.pipe(
delay(500),
tap(cbRes => {
targetRoute = cbRes.appState && cbRes.appState.target ? cbRes.appState.target : '/';
}),
concatMap(() => {
return this.isAuthenticated$;
})
);
In the AuthGuard:
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> {
return this.authService.isAuthenticated$.pipe(
tap(loggedIn => {
if (!loggedIn) {
this.authService.login(state.url);
}
})
);
In auth.service.ts:
login(redirectPath: string = '/home/dashboard') {
this.auth0Client$.subscribe((client: Auth0Client) => {
this.loading = true;
client.loginWithRedirect({
redirect_uri: environment.auth0.redirect_uri,
appState: { target: redirectPath }
});
}); }
environment.ts:
export const environment = {
...,
auth0: {
client_id: 'someSuperSecretKey',
domain: 'fooBar.auth0.com',
logout_url: 'http://localhost:4200/auth/login',
redirect_uri: 'http://localhost:4200/home/dashboard',
audience: 'https://fooBar.auth0.com/api/v2/'
}};
Some of the things I am trying currently is maybe adding some kind of loading$ observable that the AuthGuard waits on resolving so it knows once the necessary app state has been set before trying to resolve the route with checking if the user is logged in.
Any help would be greatly appreciated!