加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 2使用子路由进行身份验证

发布时间:2020-12-17 07:30:00 所属栏目:安全 来源:网络整理
导读:我有一个角度2应用程序,我需要在每个页面上进行身份验证.所以我已经实现了一个自定义的RouterOutlet来确认我在每次更改页面时都已登录. @Directive({ selector: 'auth-outlet'})export class AuthOutlet extends RouterOutlet { publicRoutes: any; private
我有一个角度2应用程序,我需要在每个页面上进行身份验证.所以我已经实现了一个自定义的RouterOutlet来确认我在每次更改页面时都已登录.
@Directive({
   selector: 'auth-outlet'
})
export class AuthOutlet extends RouterOutlet {
   publicRoutes: any;
   private parentRouter: Router;
   private authService: AuthService;
   constructor(_elementRef: ElementRef,_loader: DynamicComponentLoader,_parentRouter: Router,@Attribute('name') nameAttr: string,_authService: AuthService) {

      super(_elementRef,_loader,_parentRouter,nameAttr);
      this.parentRouter = _parentRouter;
      this.authService = _authService;
      this.publicRoutes = {
          'Login': true
      };
  }

  activate(oldInstruction: ComponentInstruction) {
      var url = this.parentRouter.lastNavigationAttempt;
      console.log('attemping to nav');
      if (!this.publicRoutes[url] && !this.authService.loggedIn){
          var newInstruction = new ComponentInstruction('Login',[],new RouteData(),Login,false,1);
          return super.activate(newInstruction);
      } else {
          return super.activate(oldInstruction);
      }
   }
}

这是一个有效的代码:
http://plnkr.co/edit/YnQv7Mh9Lxc0l0dgAo7B?p=preview

当用户未经过身份验证时,是否有更好的方法来拦截路由更改并重定向登录?

对于任何发现这一点的人来说,现在Angular 2中的答案是使用“Guards”作为新路由器的一部分.请参阅Angular 2文档:

https://angular.io/docs/ts/latest/guide/router.html#!#guards

一个基本的守卫只是实现“CanActivate”,并可以如下工作:

import {Injectable} from "@angular/core";
import {CanActivate,Router} from "@angular/router";
import {AuthService} from "../services/auth.service";

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private authService:AuthService,private router:Router){}

    canActivate(){
        if(this.authService.isAuthenticated())
            return true;

        this.router.navigate(["/login"]);
        return false;
    }
}

正如您在本示例中所看到的,我在其他地方运行了一个AuthService(实现并不重要),它可以告诉警卫用户是否已经过身份验证.如果有,则返回true,导航按常规进行.如果他们没有,我们返回false并将其重定向到登录屏幕.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读