简体   繁体   中英

Angular 6 authorization

If user is not logged in and tries to access any secure URL it should not allow him to access and must redirect to login page even if it's directly access via URL bar of browser.

I found one solution over here which resolved my problem, But only thing is whenever user tries to access authorize URL from URL bar of browser it renders index.html and nav bar components contents.

You should try canActivate. It will identify user loged-in and based on enable routes. Below is example. Create ts file for below.

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable()
export class UserAuthorised implements CanActivate {

   constructor(private router: Router) { }

   canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
      if (your condition here of if login true) {
         return true;
      } else {
         //redirect to login page.
         this.router.navigate(['/login']);
         return false;
      }
   }
}

Add above entry into list of providers in app.module.ts file. Now this class reference you need to give in routes file.

{ path: 'dashboard', component: DashboardComponent, canActivate: [UserAuthorised] },

What above will do : If user tries to access url directly routes will return false and redirect user to login page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM