angular - Angular 6:如何使用身份验证服务实现路由保护
问题描述
如何在路由保护中使用来自 auth.service.ts 的数据。从 auth.service.ts 我使用验证令牌 API 来检查有效性(在邮递员返回 {"valid" : true} 中测试)。但我不明白如何使用路由保护来实现。
auth.service.ts 验证令牌的代码。如果令牌有效返回 true
verifyToken(id:string, token: string) {
const params = new HttpParams().set('a', id).set('b', token);
this.base_url = environment.MYAPI_REST_API_URL;
this.customersObservable = this.httpClient.get(this.base_url +'/registration/application/verifyConfirmationToken', {params});
this.data = JSON.stringify(this.customersObservable);
return this.data;
}
路由守卫代码
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
this.route.queryParams.subscribe(params => {
this.id = params['a'];
this.token = params['b'];
});
if (this.auth.verifyToken(this.id,this.token)) {
// logged in so return true
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
// window.location.href='http://www.cnn.com/';
return false;
}
解决方案
是的,您可以通过创建 Auth Guard 服务来做到这一点。
// Auth Gaurd Service
// In AuthGaurdService
@Injectable()
class CanTokenActive implements CanActivate {
constructor(private currentUser: UserToken) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean>|Promise<boolean>|boolean {
// Logic to check token is exist or not.
}
}
// In routhing module
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'home',
component: Home,
canActivate: ['canTokenActive']
}
])
]
})
class AppModule {}
推荐阅读
- spring - @Configuration 是强制性的吗?
- java - 尝试将 Json 存储在 DB 中时,Ebean 'No service implementation found for SpiJsonService'
- php - Postgres 查询在“where”处或附近给出语法错误
- github - 使用 GitHub 使页面上线
- angular - 如何在 Angular 2+ 中基于组件创建模板?
- python-3.x - 在 igraph 上使用 cairo 绘图时出错:模块 'cairo' 没有属性 'Surface'
- join - awk 匹配/比较/每个文件中的 2 列(对于 2 个文件)
- geocoding - 您已超出此 API 的每日请求配额。甚至使用 api 密钥
- spring - 无法代理接口实现方法 [public final void AbstractTestNGSpringContextTests.setApplicationContext()]
- vba - 通过输入框输入的数字未链接到我在 B 列中的公式