我有以下拦截器,无论何时获得任何401(错误)响应,它都会尝试使用OAuth refresh_token
。
基本上,在第一个401请求上获得刷新令牌,并且在获得刷新令牌后,代码将等待2.5秒。在大多数情况下,第二个请求不会触发错误,但是如果发生错误(无法刷新令牌等),则用户将被重定向到登录页面。
export class RefreshAuthenticationInterceptor implements HttpInterceptor {
constructor(
private router: Router,
private tokenService: TokenService,
) {}
public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
// this catches 401 requests and tries to refresh the auth token and try again.
retryWhen(errors => {
// this subject is returned to retryWhen
const subject = new Subject();
// didn't know a better way to keep track if this is the first
let first = true;
errors.subscribe((errorStatus) => {
// first time either pass the error through or get new token
if (first) {
this.authenticationService.authTokenGet('refresh_token', environment.clientId, environment.clientSecret, this.tokenService.getToken().refresh_token).subscribe((token: OauthAccessToken) => {
this.tokenService.save(token);
});
// second time still error means redirect to login
} else {
this.router.navigateByUrl('/auth/login')
.then(() => subject.complete());
return;
}
// and of course make sure the second time is indeed seen as second time
first = false;
// trigger retry after 2,5 second to give ample time for token request to succeed
setTimeout(() => subject.next(), 2500);
});
return subject;
}),
}
}
问题出在测试之内。一切正常,除了最后检查路由器是否已实际设置为/auth/login
以外。不是,所以测试失败。
通过调试,我确定可以执行setTimeout
回调,但是subject.next()
似乎没有启动新请求。
我读到某个地方,当通常对HTTP模拟请求使用rxjs retry()
时,应该再次刷新该请求。在下面的代码中对此进行了注释,但是给出了“无法刷新已取消的请求”。
it('should catch 401 invalid_grant errors to try to refresh token the first time, redirect to login the second', fakeAsync(inject([HttpClient, HttpTestingController], (http: HttpClient, mock: HttpTestingController) => {
const oauthAccessToken: OauthAccessToken = {
// ...
};
authenticationService.authTokenGet.and.returnValue(of(oauthAccessToken));
tokenService.getToken.and.returnValue(oauthAccessToken);
// first request
http.get('/api');
const req = mock.expectOne('/api');
req.flush({error: 'invalid_grant'}, {
status: 401,
statusText: 'Unauthorized'
});
expect(authenticationService.authTokenGet).toHaveBeenCalled();
// second request
authenticationService.authTokenGet.calls.reset();
// req.flush({error: 'invalid_grant'}, {
// status: 401,
// statusText: 'Unauthorized'
// });
tick(2500);
expect(authenticationService.authTokenGet).not.toHaveBeenCalled();
expect(router.navigateByUrl).toHaveBeenCalledWith('/auth/login');
mock.verify();
})));
有人知道如何解决此测试吗?
PS:也欢迎代码本身上的任何指针:)
答案 0 :(得分:0)
最终,我将代码重构为不使用上面的first
技巧,这有助于解决问题。
对于其他在retryWhen
和单元测试中苦苦挣扎的人,这是我的最终代码:
拦截器中的代码(简体)
retryWhen((errors: Observable<any>) => errors.pipe(
flatMap((error, index) => {
// any other error than 401 with {error: 'invalid_grant'} should be ignored by this retryWhen
if (!error.status || error.status !== 401 || error.error.error !== 'invalid_grant') {
return throwError(error);
}
if (index === 0) {
// first time execute refresh token logic...
} else {
this.router.navigateByUrl('/auth/login');
}
return of(error).pipe(delay(2500));
}),
take(2) // first request should refresh token and retry, if there's still an error the second time is the last time and should navigate to login
) ),
单元测试中的代码:
it('should catch 401 invalid_grant errors to try to refresh token the first time, redirect to login the second', fakeAsync(inject([HttpClient, HttpTestingController], (http: HttpClient, mock: HttpTestingController) => {
// first request
http.get('/api').subscribe();
const req = mock.expectOne('/api');
req.flush({error: 'invalid_grant'}, {
status: 401,
statusText: 'Unauthorized'
});
// the expected delay of 2500 after the first retry
tick(2500);
// second request also unauthorized, should lead to redirect to /auth/login
const req2 = mock.expectOne('/api');
req2.flush({error: 'invalid_grant'}, {
status: 401,
statusText: 'Unauthorized'
});
expect(router.navigateByUrl).toHaveBeenCalledWith('/auth/login');
// somehow the take(2) will have another delay for another request, which is cancelled before it is executed.. maybe someone else would know how to fix this properly.. but I don't really care anymore at this point ;)
tick(2500);
const req3 = mock.expectOne('/api');
expect(req3.cancelled).toBeTruthy();
mock.verify();
})));