我有一个AuthService,基本上有两种方法: -getAuthToken(返回Promise,因此可以延迟调用/多次调用,并且在单个集合上阻塞等待) -refreshToken(还返回一个Promise,使用原始JWT上可用的刷新令牌来请求新的身份验证令牌)
我想自动
代码如下:
import { HttpEvent, HttpHandler, HttpHeaders, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { from, Observable } from "rxjs";
import { Injectable } from "@angular/core";
import { AuthService } from "./auth.service";
@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {
constructor(
private _authService: AuthService,
) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return from(this.addBearerToken(req, next));
}
private async addBearerToken(req: HttpRequest<any>, next: HttpHandler): Promise<HttpEvent<any>> {
const token = await this._authService.getAuthToken();
const headerSettings = req.headers.keys().reduce(
(acc, cur) => {
acc[cur] = req.headers.getAll(cur);
return acc;
}, {});
if (token) {
headerSettings["Authorization"] = `Bearer ${ token }`;
} else {
console.log("performing request without auth!");
}
// prevent 302 redirect to challenge on a 401
headerSettings["X-Requested-With"] = "XMLHttpRequest";
const
headers = new HttpHeaders(headerSettings),
newRequest = req.clone({ headers });
const result = next.handle(newRequest).toPromise();
result.catch(async (err) => {
if (err.status === 401) {
const
newToken = await this._authService.refreshToken();
headerSettings["Authorization"] = `Bearer ${ newToken }`;
const
updatedHeaders = new HttpHeaders(headerSettings),
updatedRequest = req.clone({ headers: updatedHeaders });
console.log("requery with new token"); // <-- I see this when I have a 401, eg by altering the auth token to be bad, whilst leaving the refresh token alone
return next.handle(updatedRequest).toPromise().then(data => {
console.log("requeried data:", data); // <-- I also see this fire, with the valid data coming back from the second request
return data; // <-- however the original caller doesn't get this data
});
}
});
return result;
}
}
我必须假定这可能是由于我将Observables和Promises混合使用了(之所以这样做是因为AuthService是异步的,使用Promises)。另外,如果没有401,则原始呼叫确实可以正确通过-就像应许链刚被放在行后一样
next.handle(newRequest).toPromise();
我想念什么?
答案 0 :(得分:2)
您在这里打破了束缚:
const result = next.handle(newRequest).toPromise();
result.catch(async (err) => {
...
});
return result;
result.catch
返回一个新的Promise,并且您的处理程序不会等待您在catch
中调用的所有操作。
因此,您可以将其编写如下:
const result = next.handle(newRequest).toPromise();
return result.catch(async (err) => {
...
});
您可能还想做的是在进行过程中不要多次调用refreshToken
cachedRequest: Promise<any>; // define prop in your class
...
if (!this.cachedRequest) {
this.cachedRequest = this.authService.refreshToken();
}
const newToken = await this.cachedRequest;
this.cachedRequest = null;
这里是Simple Demo,因此您可以对其进行测试。 (我在那里处理404,但没关系)