我正在使用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发出的请求.
履行
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']); } }); } }
providers: [ { provide: HTTP_INTERCEPTORS,useClass: ErrorInterceptor,multi: true },// ... ]
有用的链接:
>你可以在Angular documentation中找到更多关于拦截器的信息.
>验证拦截器的实现在here中找到.