【发布时间】:2017-05-12 00:48:01
【问题描述】:
我有一个应用程序,我设置了身份验证保护,以确保用户在登录之前无法访问该应用程序,就像这样
import { Injectable } from '@angular/core';
import {
CanActivate, Router,
ActivatedRouteSnapshot,
RouterStateSnapshot,
CanActivateChild } from '@angular/router';
import { AuthContext } from './auth-context.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, private authContext: AuthContext) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
// Check to see if a user has a valid JWT
if (this.authContext.userInfo !== undefined && this.authContext.userInfo.isAuthenticated) {
// If they do, return true and allow the user to load the home component
return true;
}
// If not, they redirect them to the login page
this.router.navigate(['/login']);
return false;
}
canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return this.canActivate(route, state);
}
}
我想为授权添加另一个保护,它将检查用户是否处于某个角色。目前我正在根据这个角色隐藏导航中的链接。
<div *ngIf="userInRole('Admin')">
This is secret stuff
</div>
但如果用户知道路线,他们可以将其插入 url。如何将我的“userInRole()”类型功能添加到 Guard?我必须传递角色名称并执行签入代码。 Guards 是否支持参数?
【问题讨论】:
-
这里有几个解决方案:stackoverflow.com/questions/42719445/…