我正在开发带有 Angular 6 PWA 的 Ionic 4,我在使用拦截器捕获 401/403 页面请求时遇到了一些困难。
这是我的拦截器代码:
import { HttpInterceptor, HttpRequest, HttpHandler, HttpUserEvent, HttpEvent } from "@angular/common/http";
import { Observable, empty } from "rxjs";
import { tap } from 'rxjs/operators';
import { Injectable } from "@angular/core";
import { Router } from "@angular/router";
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private router: Router) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.headers.get('No-Auth') == "True") {
return next.handle(req.clone());
}
if (localStorage.getItem('userToken') != null) {
const clonedreq = req.clone({
headers: req.headers.set("Authorization", "Bearer " + localStorage.getItem('userToken'))
});
return next.handle(clonedreq).pipe
(
tap(
succ => { },
err => {
if (err.status === 401 || err.status === 403){
localStorage.removeItem('userToken');
this.router.navigate(['/account/login']);
return empty();
}
}
)
);
}
else {
localStorage.removeItem('userToken');
this.router.navigate(['/account/login']);
return empty();
}
}
}
所以这似乎几乎按要求工作,因为它会将 token 添加到 http 请求(如果它存在于 LocalStorage 中)并且我的 WepAPI 会根据请求验证它。
但是,如果我登录并导航到一个我不应该被允许的页面(403 错误),或者如果我没有登录并转到一个安全页面(401)——拦截器捕获这个罚款,localstorage项目被删除,我被重定向到登录页面。这一切都很好。
问题是,我试图导航到的页面,例如抛出 401/403 状态代码的新闻源现在缓存在 DOM 中。所以现在我在登录页面上,我登录正常,我重定向回 NewsFeed 页面,但该页面是空白的,因为它没有呈现数据,因为它最初被 401/403 错误阻止。
如何在重定向前成功登录后从 DOM 缓存中删除页面。
我累了: this.nav.navigateRoot('/newsfeed'); 但它似乎仍然呈现一个空白的 Newsfeed 页面。
auth.guard.ts 文件
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Storage } from '@ionic/storage';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router : Router, private storage: Storage){}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
if (localStorage.getItem('userToken') != null)
{
return true;
}
this.router.navigate(['/account/login']);
return false;
}
}
有什么想法吗???
谢谢
最佳答案
糟糕,我的 AuthGuard 没有在正确的路线上开火。
一旦我解决了这个问题,它就会按预期工作。
谢谢
罗伊
关于angular - Ionic 4/Angular 6 - 使用拦截器在 401/403 上重定向登录页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53801258/