【发布时间】:2019-10-01 00:14:22
【问题描述】:
我目前正在实现一个身份验证系统,其中用户登录并从服务器接收 JWT 令牌,该令牌存储在 localStorage 中。我还编写了一个自定义 HttpInterceptor,它将用户的令牌附加到传出的 HTTP 请求中。这适用于本地端点,但是我也有一个 GET 请求从 GitHub 的 API 获取每个用户的头像,并且由于拦截器,这不再有效。我从 GitHub 收到 401 身份验证错误。
这是来自 HttpInterceptor 的代码:
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const idToken = localStorage.getItem("access_token");
if (idToken && req.url.includes("localhost")) {
const cloned = req.clone({
headers: req.headers.set("Authorization", `Bearer ${idToken}`)
});
return next.handle(cloned);
} else {
return next.handle(req);
}
}
}
以下是发送到 GitHub 的请求标头:
Accept: application/json, text/plain, */*
Authorization: token ... (removed for privacy)
Content-Type: application/json
Origin: http://localhost:4200
Referer: http://localhost:4200/contacts
User-Agent: ...(removed for privacy)
这是来自 GitHub API 的响应:
Request URL: https://api.github.com/users/...
Request Method: GET
Status Code: 401 Unauthorized
Remote Address: 192.30.253.117:443
Referrer Policy: no-referrer-when-downgrade
这是获取 GitHub 头像的服务中的代码:
const githubOptions = {
headers: new HttpHeaders({
"Content-Type": "application/json",
Authorization: "token ..." // removed for privacy
})
};
@Injectable({
providedIn: "root"
})
export class ContactServiceService {
constructor(private http: HttpClient) {}
...
getGithub(user: string): Promise<any> {
return this.http
.get<any>(`https://api.github.com/users/${user}`, githubOptions)
.toPromise();
}
}
奇怪的是,如果我在 Chrome 网络控制台中双击 HTTP 请求,它会正常运行并返回所需的响应。但无论出于何种原因,HttpInterceptor 都会阻止它在我的代码中通过。
非常感谢任何帮助!
【问题讨论】:
标签: angular http authentication jwt angular-http-interceptors