我正在使用来自 auth0 的 angular2-jwt 包。一切正常,但现在我想知道如何重定向当前在某条路径上的用户,该路径由我的 auth 守卫保护,在其他地方。现在它只是在用户试图到达 protected 路径时重定向。

我知道我可以在我的组件中隐藏对象,但是我必须在每个 protected 组件中都这样做,这不是很清楚。

以下是我的路线:

    const appRoutes: Routes = [
    {path: 'login', component: LoginComponent},
    {path: 'register', component: RegisterComponent},
    {path: '', component: HomeComponent},
    {path: 'user/edit', component: EditProfileComponent, canActivate: [AuthGuard]},
];

这是我的 guard 服务:
...

    @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(禁止访问,未授权访问)。通过这样的实现,您还可以在每次向服务器发送请求时设置请求的授权 header 。

确保您在应用程序中使用 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']);
            }
        });
    }
}

第2步,使用错误拦截器:
providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: ErrorInterceptor,
      multi: true
    },
    // ...
]

有用的链接:
  • 您可以在 Angular documentation 中找到有关拦截器的更多信息。
  • here 中找到了身份验证拦截器的实现。
  • 关于angular2-routing - 当 JWT token 过期并且他当前位于 protected 位置时,Angular2 将用户重定向到某个地方,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42330846/

    10-11 11:27