Auth0 Home Blog Docs

Angular login automatically

angular

#1

Hello,

Rather than having a login button on my app, I’d like the user to be automatically redirected to the Auth0 login page when they navigate to my app.

I’m currently solving this by adding a key/value to session storage when my app initialises (when ngOnInit() is called).

Here is my code:

ngOnInit() {
  if (!sessionStorage.getItem('isLoggedIn')) {
    sessionStorage.setItem('isLoggedIn');
    this.authService.login(); // this calls auth0.authorise()
  }
}

This seems to be a bit flakey!

Can anyone suggest a better way of doing this?

Thanks,

Ben


#2

The approach, in general, would be to make all sections (routes) of your application “private” (including the home page) so that when an anonymous user hits any protected resource the login action is triggered.
Take a look at the responses at https://stackoverflow.com/questions/20969835/angularjs-login-and-authentication-in-each-route-and-controller for some approaches.


#3

Hi Nicolas,

Thank you for replying to my post. This is a great idea, however my App is written in Angular 7 (not AngularJS).

Do you have an example in Angular 7?

I’ve attempted this but I’m getting stuck in a loop. When I’m redirected back to my app, the handleAuthentication() method is called which is async. At this point, my route guard code has already executed.

Here is my route guard code:

@Injectable()
export class AuthGuard implements CanActivate {

constructor(private authService: AuthService) {
}

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (!this.authService.isAuthenticated()) {
this.authService.login();
return false;
}
return true;
}

}

Hope you can help :slight_smile:


#4

How about using route guards, as explained here by Ryan Chenkie: https://medium.com/@ryanchenkie_40935/angular-authentication-using-route-guards-bf7a4ca13ae3