首页 > 解决方案 > 令牌过期时如何防止用户路由

问题描述

我正在开发 Angular 7 应用程序

标签: angularangular6angular5angular-routingangular-router-guards

解决方案


如果您使用CanActivate,那么您可能必须在每次路由更改时进行网络调用以探测身份验证是否已过期。至少这是我能想到的。

如果可能,您可以在后端检查这一点,并使用 401 Unauthorized access status code 拒绝所有调用、API 调用和所有其他调用。

有了这个,你可以设置一个拦截器来处理 401 并将用户重定向到登录页面或添加一个逻辑来刷新你喜欢的令牌。您还可以传递Location标头并将其用于重定向。

import {throwError as observableThrowError,  Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    constructor(private router: Router) {}
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).pipe(
            catchError((err: any, caught) => {
                if (err instanceof HttpErrorResponse) {
                    if (err.status === 401) {
                       // Redirect or refresh token.
                    }
                    return observableThrowError(err);
                }
            }));
    }
}

我确实希望那里会有其他解决方案。


推荐阅读