[英]AuthService in Angular2
我目前正在用angular2構建應用程序。 因此,我實現了一個用於處理登錄,注冊等的AuthService。如果在id_token(angular2-jwt)中簽名的用戶存儲在localStorage中。 用戶的角色和權限存儲在AuthService.userRoles
和AuthService.userPerms
。
布爾屬性AuthService.isAuthenticated
使用angular2-jwt中的功能tokenNotExpired()
,如果用戶已注銷或本地存儲中存儲的令牌過期,則返回false。 如果將登錄AuthService.isAuthenticated
的用戶更新為true
;
我得到了使用AuthGuard的路由,該路由僅允許通過身份驗證的用戶通過檢查AuthService.isAuthenticated
屬性來激活此路由。
如果某條路線如下所示:
{
path: "somewhere",
component: SomeComponent,
canActivate: [AuthGuard],
data: {
permissions: [
"add:some",
"edit:some"
]
}
}
相同的AuthGuard通過將AuthService.userPerms
與路由的data.permissions
匹配來檢查當前登錄的用戶是否具有所需的權限。 哪個也可以。
我的應用程序使用“主要組件”。 這主要成分是“公”, 不使用AuthGuard。 它在主app.module
內部引導, 沒有自己的路由 。 在這個主要父組件的模板內部,我得到了應用程序范圍的導航。
在此導航的內部是路由的按鈕,這些按鈕受AuthGuard保護,因此僅當用戶登錄且具有特定權限或角色(如果該路由需要)時才可以訪問。 例如
<button [routerLink]="/somewhere">Somewhere</button>
如果用戶單擊此按鈕且未獲得授權,則將其重定向到unauthorized
路由。 到目前為止工作
我想通過僅在用戶能夠激活路線的情況下使這些按鈕可見來防止出現這種情況 。
<button [routerLink]="/somewhere"
*ngIf="isAuthorized["buttonSomewhere"]">
Somewhere
</button>
因此,在主AppComponent(處理導航)內部,我想檢查模板內每個按鈕的userPermissions並將結果存儲在這樣的對象中:
/* AppComponent */
public isAuthorized = {
buttonSomewhere = true;
}
此項檢查由AuthService.isAuthorized(theRouteToBeActivated)
處理,該方法在AppComponent構造函數內部調用,並將路由data.permission
與AuthService.userPerms
存儲的用戶權限進行AuthService.userPerms
。
問題是,由於AppComponent是公共的,並且不受AuthGuard保護,因此構造函數在用戶未登錄時運行,這是正確的。 此時,被調用的AuthService.isAuthorized(theRouteToBeActivated)
返回false並將值存儲在
/* AppComponent */
public isAuthorized = {
buttonSomewhere = false;
}
這也是正確的。 因此,如果用戶退出,他將看不到無法激活的路由按鈕。
但是問題是:在用戶登錄了AppComponents構造函數中調用的AuthService.isAuthorized(theRouteToBeActivated)
之后, 不會再次調用它,並且
/* AppComponent */
public isAuthorized = {
buttonSomewhere = false;
}
保持原樣。 但是在用戶登錄后,需要再次調用該函數,以便該函數返回true並進行更改
/* AppComponent */
public isAuthorized = {
buttonSomewhere = true;
}
這樣, 登錄用戶即可看到模板中的按鈕。 目前,我需要在瀏覽器中重新加載應用程序。 然后,登錄用戶可以看到這些按鈕。 但是我不想重新加載。
我該如何解決?
您可以通過在route參數中使用授權的防護來實現。 認證和授權之間是有區別的。 檢查以下鏈接。
https://angular.io/docs/ts/latest/guide/router.html#!#can-activate-guard
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.