angular - 令牌过期时如何防止用户路由
问题描述
我正在开发 Angular 7 应用程序
- 我正在使用 JSON Web 令牌 (JWT) 来保护我的 Angular 应用程序
- 我想检查天气令牌是否已过期,如果已过期,我想阻止用户路由。除了主页和主页旁边
- 我只是希望令牌在过期时不会有用,因此应该将用户视为“未经过身份验证”。
- 我使用 npm install --save @auth0/angular-jwt@beta 尝试了相同的操作,但我不想使用任何依赖项做同样的事情
- 我想使用路由保护来做到这一点,我用 CanActivate 尝试过,但它不起作用
解决方案
如果您使用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);
}
}));
}
}
我确实希望那里会有其他解决方案。
推荐阅读
- c# - 如何将2个列表中的元素添加到第三个?
- apache - 阻止访问子文件夹,将所有通配符子文件夹重定向到同名子域
- azure - 在 azure devops 中上传字幕和视频
- email - 为什么 Sieve 在 base64 主题行上表现异常?
- java - Springboot中Flyway时的Java API调用
- javascript - 启动机器人时出现“Client.js”错误和 Sqlite 错误
- io - I/O 系统,计算周期寄存器和预分频值
- javascript - 通过变量更改嵌入文本
- amazon-web-services - 来自不同 AWS 账户的交叉堆栈引用
- c# - C# Visual Studio 2010 与 2019 中的计时器实现