简体   繁体   English

Angular 6授权

[英]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. 如果用户未登录并尝试访问任何安全URL,则即使该用户通过浏览器的URL栏直接访问,也不应允许他访问,并且必须重定向到登录页面。

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. 我在这里找到了一个解决方案,它解决了我的问题,但是唯一的事情是,每当用户尝试从浏览器的URL栏访问授权URL时,它都会呈现index.html和导航栏组件的内容。

You should try canActivate. 您应该尝试canActivate。 It will identify user loged-in and based on enable routes. 它将基于启用路由来标识用户已登录。 Below is example. 以下是示例。 Create ts file for below. 为以下创建ts文件。

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. 将以上条目添加到app.module.ts文件中的提供程序列表中。 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. 上面的操作:如果用户尝试直接访问url,则路由将返回false并将用户重定向到登录页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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