【发布时间】:2020-01-09 19:49:32
【问题描述】:
我实现了 AuthTokenInterceptor 如下。我的问题是授权令牌无法正确转发到服务器端。我确信在我将请求传递给 next.handler() 之前,我可以通过 request.headers.get("Authorization") 获取身份验证令牌。
我发现请求已经发送了两次,第一个没有 Authorization 标头,但第二个有标头。
我从管道中删除了重试,但仍有两个请求发送到服务器端。
我的项目有一个特殊情况。我使用了第三方 i18n 工具,它需要来自“@angular/http”的旧 HttpModule。所以我同时导入了 HttpModule 和 HttpClientModule。
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (this.authService.getAccessToken()) {
request = this.addToken(request);
}
return next.handle(request).pipe(catchError(error => {
if (error instanceof HttpErrorResponse
&& ( error.status === 401 || error.status == 403) ) {
if ( error.status == 401 )
return this.handle401Error(error, request, next);
else
return this.handle403Error(error, request, next);
} else {
return throwError(error);
}
}));
}
private addToken(request: HttpRequest<any>): HttpRequest<any> {
const tokenName = this.authService.getAuthorizationTokenName();
const tokenValue = this.authService.getAuthorizationTokenValue();
// Clone the request and replace the original headers with
// cloned headers, updated with the authorization.
const authReq = request.clone({
headers: request.headers.set(tokenName, tokenValue)
});
return authReq;
}
【问题讨论】:
-
您的第一个请求可能是在客户端地址与 API 地址不匹配时使用的 OPTIONS 调用,以检查 CORS 策略。这是浏览器发出的,与Angular本身无关。
-
是的,第一个请求是 OPTIONS 请求。我已经在服务器端允许了 OPTIONS 请求,但没有进行身份验证。
标签: angular header authorization token httpclient