Redirect to Previous URL after Login with Auth Guard

Redirect to Previous URL after Login with Auth Guard

In this post I’ll show you how to redirect a user back to their originally requested url / route after logging into an Angular 2 application, this is done with the help of an Auth Guard and a Login Component.

Angular 2 Auth Guard

Guards in Angular 2 are used to protect routes, there are a few different guard types depending on the specific behaviour you want to implement, in this example I’m using a CanActivate guard which implements a single canActivate() method that enables you to check if a route can be activated or not, which in this case is if the user is authenticated or not.

If the user isn’t authenticated, the auth guard also redirects them to the ‘/login’ route and includes the original (previous) url in the ‘returnUrl’ parameter. The original url is accessible in the auth guard via the ‘state: RouterStateSnapshot’ parameter that is passed to the canActivate() method.

Auth Guard that passes original URL to login component

  1. import { Injectable } from ‘@angular/core’;
  2. import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from ‘@angular/router’;
  3. @Injectable()
  4. export class AuthGuard implements CanActivate {
  5. constructor(private router: Router) { }
  6. canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  7. if (localStorage.getItem(‘currentUser’)) {
  8. // logged in so return true
  9. return true;
  10. }
  11. // not logged in so redirect to login page with the return url and return false
  12. this.router.navigate([‘/login’], { queryParams: { returnUrl: state.url }});
  13. return false;
  14. }
  15. }

Angular 2 Login Component

The login component is a standard Angular 2 ‘controller’ component that implements the behaviour for a login form.

In the ngOnInit() method the component gets the original url that was passed from the Auth Guard as a route parameter and stores it in the local returnUrl property, if the original url is empty the returnUrl defaults to the home page route (‘/’). Parameters for the current route are accessible via the ‘private route: ActivatedRoute’ property that’s injected in the component constructor.

In the login() method the component uses the authenticationService to authenticate the username and password, on successful login the user is redirected to the returnUrl. For more details on the authentication service go to the user registraion and login example link at the top of the post.

Login Component that redirects to the previous / original URL after login

  1. import { Component, OnInit } from ‘@angular/core’;
  2. import { Router, ActivatedRoute } from ‘@angular/router’;
  3. import { AlertService, AuthenticationService } from ‘../_services/index’;
  4. @Component({
  5. moduleId:,
  6. templateUrl: ‘login.component.html’
  7. })
  8. export class LoginComponent implements OnInit {
  9. model: any = {};
  10. loading = false;
  11. returnUrl: string;
  12. constructor(
  13. private route: ActivatedRoute,
  14. private router: Router,
  15. private authenticationService: AuthenticationService,
  16. private alertService: AlertService) { }
  17. ngOnInit() {
  18. // reset login status
  19. this.authenticationService.logout();
  20. // get return url from route parameters or default to ‘/’
  21. this.returnUrl = this.route.snapshot.queryParams[‘returnUrl’] || ‘/’;
  22. }
  23. login() {
  24. this.loading = true;
  25. this.authenticationService.login(this.model.username, this.model.password)
  26. .subscribe(
  27. data => {
  28. // login successful so redirect to return url
  29. this.router.navigate([this.returnUrl]);
  30. },
  31. error => {
  32. // login failed so display error
  33. this.alertService.error(error);
  34. this.loading = false;
  35. });
  36. }
  37. }

About the author

admin administrator

Leave a Reply