[英]Verify token with API in Angular8 canActivate method of AuthGuard
[英]Angular2 routing canActivate and AuthGuard (JWT) with user role parameter
在這個使用JWT身份驗證的exaple項目中 ,我們將了解如何僅允許經過身份驗證的用戶訪問某些路由:
import { RouterConfig } from '@angular/router';
import { Home } from './home';
import { Login } from './login';
import { Signup } from './signup';
import { AuthGuard } from './common/auth.guard';
export const routes: RouterConfig = [
{ path: '', component: Login },
{ path: 'login', component: Login },
{ path: 'signup', component: Signup },
{ path: 'home', component: Home, canActivate: [AuthGuard] },
{ path: '**', component: Login },
];
我想更進一步,並指出用戶角色有什么“訪問”路由 - 但我不知道如何將參數傳遞給canActivate AuthGuard(src) 。 所以我想實現這樣的目標(例如我有兩個角色:Admin和Employee):
{ path: 'home', component: Home, canActivate: [AuthGuard] },
{ path: 'users', component: AdminUsers, canActivate: [AuthGuard('Admin')] },
{ path: 'users', component: Employees, canActivate: [AuthGuard('Employee')] },
我的AuthGuard看起來像這樣(userRole(= Admin或Employee或null)將參數傳遞給AuthGuard):
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(userRole) {
if (!userRole || JWT.user().role == userRole) {
return true;
}
this.router.navigate(['/login']);
return false;
}
}
其中JWT.user.role是幫助程序,它讀取存儲在JWT令牌中的用戶角色。 有沒有辦法像上面的想法做類似的事情?
您可以使用如下角色設置路徑的data
參數
const appRoutes: Routes = [ { path: 'account/super-secure', component: SuperSecureComponent, canActivate: [RoleGuard], data: { roles: ['super-admin', 'admin'] } }];
然后在canActivate
of RoleGuard
有這個:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { let roles = route.data["roles"] as Array<string>; return (roles == null || roles.indexOf("the-logged-user-role") != -1); }
我認為這可能是另一種方式,而不是為每個角色創造防范。 我實際上會采取這種潰敗,因為它需要更少的代碼並且非常好地處理問題。
CanActivate
的簽名不允許您按照CanActivate
意願傳遞userRole
。 https://github.com/angular/angular/blob/2.0.0-rc.4/modules/%40angular/router/src/interfaces.ts#L54
最好為每個用戶角色案例分別執行類。 這也是官方文檔中的指導: https : //angular.io/docs/ts/latest/api/router/index/CanActivate-interface.html
注意 :適用於angular-rc.4 <
@KamilKiełczewski,@ NikolayRusev,
添加路由附加數據與路由數組:
...
{
path: "customers",
component: CustomersCmp,
data: { roles: ["admin"] }
},
...
在CanActivate中,您可以從第一個參數獲取path
,在路徑配置中搜索相同的路徑,並從數據中獲取您描述的角色:
public canActivate(route: ActivatedRouteSnapshot): boolean {
let path = route._urlSegment.pathsWithParams[0].path;
let roles;
if (route._routeConfig.path == path) {
roles = route._routeConfig.data.roles
} else {
roles = route._routeConfig.children.find(_route => _route.path == path).data.roles;
}
if (...) {
return true;
}
return false;
}
當然最好避開私有財產,你可以,但我不記得我是怎么做到的。
但是對於我的作品,我以不同的方式重新制作它。 這種方法的巨大缺點,我的意思是基於角色的防護,是每個具有不同角色的用戶都可以看到所有路由,如果您在一個組件中自動而不是手動渲染它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.