Angular login automatically

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

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 javascript - AngularJS- Login and Authentication in each route and controller - Stack Overflow for some approaches.

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:

How about using route guards, as explained here by Ryan Chenkie: Angular Authentication: Using Route Guards | by Ryan Chenkie | Medium

Hey @ben.bullock!

Have you had a chance to go through the article Nico provided?

Hey @konrad.sopala, yes @nicolas_sabena’s article was very helpful thank you :slight_smile:

2 Likes

Great! Glad you made it work!

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.