【发布时间】:2018-10-29 08:08:17
【问题描述】:
我有一个角度应用程序,它使用 oAuth 来检查用户是否有效。 AuthGuard 和 AuthService 负责将用户路由到第三方登录页面,一旦用户获得令牌,他就会被路由回 Angular 应用程序,在该应用程序中通过对节点 API 进行 REST 调用来验证令牌。如果token有效,则token保存在sessionStorage中,用户登录。
下面所有的路由都有 AuthGuard,所以每次用户登录后尝试渲染页面时,AuthService 都会将令牌发送给 API 以检查其有效性。当用户已经登录时,如何避免在渲染每个路由之前进行 API 调用以进行令牌验证。
{
path: '',
component: LoginComponent,
},
{
path: 'user',
component: UserComponent,
canActivate: [AuthGuard]
},
{
path: 'dashboard',
component: dashboardComponent,
canActivate: [AuthGuard],
children: [
{
path: '',
loadChildren: './other-layout/other-layout.module#otherModule'
}
]
}
以下是 AuthGuard 代码:
@Injectable()
export class AuthGuard implements CanActivate {
params: any;
constructor(private auth: AuthService,
private router: Router,
private route: ActivatedRoute){
}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return new Promise((resolve, reject)=>{
let authenticated = this.authService.handleAuthentication()
authenticated.then((result) =>{
if(result){
resolve(true);
}else{
console.log('Authenication failed. User is being routed to third party site for authentication')
this.authService.routeForOAuth();
reject(false);
}
})
})
}
}
验证服务代码:
public handleAuthentication(): any {
return Promise((resolve, reject)=>{
if (window.location.hash.includes("access_token")){
let windowlocation = window.location.hash.split('&');
this.validateToken(windowlocation[0].split('=')[1],(result) => {
resolve(result);
})
} else if (sessionStorage.getItem('access_token') != null){
this.validateToken(sessionStorage.getItem('access_token'), (result) => {
resolve(result);
})
} else{
resolve(false);
}
})
}
【问题讨论】:
-
你能在你的 authGuard 中发布你的
canActivate方法吗? -
我已在问题中添加了 AuthGuard 代码。
-
你的身份提供者是什么?
-
它是一个内部 OAuth 提供者(企业范围)
标签: angular oauth-2.0 angular2-routing