angular2-routing – 当JWT令牌到期时,Angular2将用户重定向到某
发布时间:2020-12-17 17:09:11 所属栏目:安全 来源:网络整理
导读:我正在使用auth0的angular2-jwt软件包.一切正常,但现在我想知道如何重定向用户,目前正在某个路径上,用我的auth后卫保护,在其他地方.现在,当用户试图进入受保护的路径时,它正在重定向. 我知道我可以隐藏组件中的对象,但是我必须在每个受保护的组件中执行此操
|
我正在使用auth0的angular2-jwt软件包.一切正常,但现在我想知道如何重定向用户,目前正在某个路径上,用我的auth后卫保护,在其他地方.现在,当用户试图进入受保护的路径时,它正在重定向.
我知道我可以隐藏组件中的对象,但是我必须在每个受保护的组件中执行此操作,这不是那么清楚. 这是我的路线: const appRoutes: Routes = [
{path: 'login',component: LoginComponent},{path: 'register',component: RegisterComponent},{path: '',component: HomeComponent},{path: 'user/edit',component: EditProfileComponent,canActivate: [AuthGuard]},];
这是我的警卫服务: ...
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService,private router: Router) {
}
canActivate() {
if (this.auth.loggedIn()) {
return true;
}
this.router.navigate(['/']);
return false;
}
}
解决方法
Http拦截器
你可以做的是实现一个HTTP拦截器. 此HTTP拦截器可以检查错误代码,如401(未经过身份验证)和/或403(fobidden,未授权访问).通过这样的实现,您还可以在每次向服务器发送请求时设置请求的授权标头. 确保在应用程序中使用HttpClient.拦截器仅侦听HttpClient发出的请求. 履行 第1步,创建一个错误拦截器: import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { HttpEvent,HttpInterceptor,HttpHandler,HttpRequest } from '@angular/common/http';
import { HttpErrorResponse } from '@angular/common/http';
import 'rxjs/add/operator/do';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private router: Router) { }
intercept(req: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).do(event => { },err => {
if (err instanceof HttpErrorResponse && err.status == 401) {
this.router.navigateByUrl('/login');
} else if (err instanceof HttpErrorResponse && err.status == 403) {
this.router.navigate(['/not-authorized']);
}
});
}
}
第2步,使用错误拦截器: providers: [
{
provide: HTTP_INTERCEPTORS,useClass: ErrorInterceptor,multi: true
},// ...
]
有用的链接: >你可以在Angular documentation中找到更多关于拦截器的信息. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
