我试图避免401错误时令牌在1小时后终止。
这是我的代码。
auth-interceptor.ts
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/do';
import { Router } from '@angular/router';
import { AuthService } from 'app/univers-auth/auth.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
auth: any;
constructor(private router: Router, private authService: AuthService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
const auth = this.authService.auth;
const signInUserSession = auth.getCachedSession();
if (!signInUserSession.isValid()) {
auth.refreshSession(signInUserSession.getRefreshToken().getToken());
}
const authToken = signInUserSession.getAccessToken().getJwtToken();
const header = { Authorization: 'Bearer ' + authToken };
const currentrole = localStorage.getItem('current-role');
if (currentrole !== null) {
header['currentRole'] = currentrole;
}
const authReq = req.clone({ setHeaders: header });
return next.handle(authReq).do(event => { }, err => {
if (err instanceof HttpErrorResponse && err.status === 401) {
this.router.navigate(['logout']);
}
});
}
}
但是在获得刷新会话的响应之前,api失败并带有旧令牌。
有人可以在这里帮助我吗?