.net 6 cors 预检选项请求 401 未经授权错误的问题

发布于 2025-01-09 17:23:55 字数 2044 浏览 1 评论 0原文

我正在发出 CORS PUT 请求并将 Content-Type 标头设置为 json。这会触发预检选项请求。在我的程序文件中(见下图)我得到了 401 Unauthorized error(见图片)。我该怎么做才能让它发挥作用

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Internal Store Data API", Version = "v1" });
});

builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
   .AddNegotiate();

builder.Services.AddAuthorization(options =>
{
    // By default, all incoming requests will be authorized according to the default policy.
    options.FallbackPolicy = options.DefaultPolicy;
});

builder.Services.AddCors(options =>
{
    options.AddPolicy(
      "CorsPolicy",
      builder => builder
                .AllowAnyMethod()
               .AllowAnyHeader()
               .SetIsOriginAllowed(origin => true) // allow any origin
               .AllowCredentials()
      );
});



// Start Database Connection
// End Database Connection

// Start Repositories
// End Repositories

// Start UseCases
// End UserCases


var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment() || app.Environment.IsProduction())
{
    app.UseDeveloperExceptionPage();
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "Internal Store Data API V1");
        c.RoutePrefix = String.Empty;
    });
}

app.UseHttpsRedirection();
app.UseCors("CorsPolicy");

app.UseAuthorization();
app.UseAuthentication();
app.MapControllers();

app.Run();

在此处输入图像描述

我尝试添加此内容,但仅此而已在 localhost 上工作(当我在 VS 上运行它时,但在托管时则不然)

"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": true,
"iisExpress": {
  "applicationUrl": "http://localhost:8791/",
  "sslPort": 0
}

请帮助

I am making a CORS PUT request and setting the Content-Type header to json. This triggers a Preflight OPTIONS request to fire. In my program file I have (see below) I getting back 401 Unauthorized error (see image) . What can I do to get this to work

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Internal Store Data API", Version = "v1" });
});

builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
   .AddNegotiate();

builder.Services.AddAuthorization(options =>
{
    // By default, all incoming requests will be authorized according to the default policy.
    options.FallbackPolicy = options.DefaultPolicy;
});

builder.Services.AddCors(options =>
{
    options.AddPolicy(
      "CorsPolicy",
      builder => builder
                .AllowAnyMethod()
               .AllowAnyHeader()
               .SetIsOriginAllowed(origin => true) // allow any origin
               .AllowCredentials()
      );
});



// Start Database Connection
// End Database Connection

// Start Repositories
// End Repositories

// Start UseCases
// End UserCases


var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment() || app.Environment.IsProduction())
{
    app.UseDeveloperExceptionPage();
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "Internal Store Data API V1");
        c.RoutePrefix = String.Empty;
    });
}

app.UseHttpsRedirection();
app.UseCors("CorsPolicy");

app.UseAuthorization();
app.UseAuthentication();
app.MapControllers();

app.Run();

enter image description here

I tried adding this but it only works on localhost ( when I running it on VS but not when it hosted )

"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": true,
"iisExpress": {
  "applicationUrl": "http://localhost:8791/",
  "sslPort": 0
}

Please help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一个人的旅程 2025-01-16 17:23:55

我看不到您实际上正在添加任何来源尝试这个,添加您允许的来源

    /*
    * cors
    * 
    */
    string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
    
    string[] origin = { your allowed origins here };
    
    builder.Services.AddCors(options =>
    {
        options.AddPolicy(name: MyAllowSpecificOrigins,
                          builder =>
                          {
                              builder.WithOrigins(origin
                                                  )
                                                   .AllowAnyHeader()
                                                   .AllowAnyMethod();
                          });
    });

...

app.UseCors(MyAllowSpecificOrigins);

我不确定您的解决方案的这一部分:

 .SetIsOriginAllowed(origin => true) // allow any origin

虽然有这种方法可能是您想要的方法:

  ...
  .AllowAnyOrigin()

编辑
虽然看你的问题看起来根本不像 CORS,但它看起来像是身份验证问题,但你没有通过身份验证

i cant see that you are actually adding any origins try this, adding your allowed origins in

    /*
    * cors
    * 
    */
    string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
    
    string[] origin = { your allowed origins here };
    
    builder.Services.AddCors(options =>
    {
        options.AddPolicy(name: MyAllowSpecificOrigins,
                          builder =>
                          {
                              builder.WithOrigins(origin
                                                  )
                                                   .AllowAnyHeader()
                                                   .AllowAnyMethod();
                          });
    });

...

app.UseCors(MyAllowSpecificOrigins);

i am not sure on this part of your solution:

 .SetIsOriginAllowed(origin => true) // allow any origin

there is this method though which might be the one you want:

  ...
  .AllowAnyOrigin()

EDIT
though looking at your issue doesnt even look like CORS it looks like authentication issue, you arent getting past authentication

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文