gpt4 book ai didi

c# - 为什么Angular的请求头修改会抛出option 401错误

转载 作者:太空宇宙 更新时间:2023-11-03 12:07:16 26 4
gpt4 key购买 nike

我想修改 Angular HttpRequest 的 header ,但在 chrome 中抛出 OPTIONS 401 错误。

我使用在 http://localhost:4200 上运行的 Angular 7 客户端和运行在 http://localhost:5000 上的 .net core 2.1

我遇到的问题是:

如果我不使用 httpInterceptor(这意味着我不修改 httpRequest header ),请求将继续到服务器并返回值。

但如果我尝试修改 header ,则会出现以下错误:

Options http://localhost:5000/api/value/2 401 (Unautorized)
Failed to load http://localhost:5000/api/values/2:
Response to preflight request doesn't pass access control check:
'No Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:4200' is therefore not allowed to access.
The response had Http status code 401.

这有点奇怪,因为如果我克隆 Chrome 创建的 httpRequest,当我不修改 header 时,请求会成功。但是当我尝试修改它时,它失败了。

此外,我确实尝试将“Access-Control-Allow-Origin” header 添加到请求中。但是我又一次收到同样的错误。

我使用 HttpInterceptor 来修改 HttpRequest header 。

export class HeaderInterpreter  implements HttpIntterceptor {

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

If (req instanceof HttpRequest && localStorage.getItem("token")){
const modReq = req.clone({
headers: req.headers.set('Authorization', `Bearer ${localStorage.getItem("token")}`)
})
return next.handle(modReq);
}
return next.handle(req);
}

在服务器端我做了以下事情:

public void ConfigureServices(IserviCollection services)
{
...
services.addCors();
...
services.addMvc();
}

public void Configure(IApplicationBuilder app)
{
...

app.UseCors(builder =>
builder.withOrigins("http://localhost:4200"))
.allowAnyHeader();

...

app.UseMvc();
}

我还在 Angular 的 http.get 函数和服务器上的 windows 身份验证上使用了 withCredentials: true

最佳答案

出现这个问题有几个原因:

首先,我同时使用 windows 身份验证和 jwt token ,因此我在 program.cs 上使用“UseHttpSys”启用了 windows 身份验证。

其次,因为我同时使用了 Windows 身份验证和 jwt token ,所以我无法在授权 header 上发送 jwt token ,相反我在我自己的自定义 header 上发送了它。

第三,因为我发送了一个带有授权 header 的请求,Chrome 发送了一个预检请求,用于 Cors 目的。但是因为预检请求(又名选项)没有与授权 header 一起发送,服务器拒绝了它(因为它只授予经过身份验证的用户权限)。所以我需要在服务器上启用匿名访问。

第四,我使用中间件检查请求是否预检,如果不是,我会检查请求是否来自经过身份验证的用户。 (因为我允许匿名访问,所以chrome先发送一个未经认证的请求,当它被中间件拒绝后,Chrome重新发送一个经过认证的请求)。

参见引用资料 https://github.com/aspnet/CORS/issues/60#issuecomment-262880489

关于c# - 为什么Angular的请求头修改会抛出option 401错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54310706/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com