gpt4 book ai didi

c# - 无法在 asp.net core 中为身份服务器 4 启用 CORS

转载 作者:行者123 更新时间:2023-11-30 18:17:35 26 4
gpt4 key购买 nike

好的,我已经为我的 dot net 核心 API 添加了 CORS 策略,但不知何故这些 CORS 策略不适用于身份服务器 4 端点。我在尝试注册用户时有以下 api:

    [EnableCors("AllowAllCorsPolicy")]
[Route("api/User")]
public class UserController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private IUserServices _userService;
public UserController(UserManager<ApplicationUser> userManager, IUserServices userService)
{
_userManager = userManager;
_userService = userService;
}

[HttpPost]
public async Task<int> Post([FromBody]User userInfo)
{
var user = new ApplicationUser{ UserName = userInfo.Name, Email = userInfo.Email,
UserTypeId = Constant.User, CustomerId = userInfo.CustomerId };

//Follwing 3 lines give CORS issue.
await _userManager.AddToRoleAsync(user, Constant.User);
var userClaim = new Claim(Constant.User, user.Email.ToString(), ClaimValueTypes.Integer);
await _userManager.AddClaimAsync(user, userClaim);

// var userObj = _userService.AddNewUser(userInfo);
}

现在,如果我使用上述身份服务器方法(AddToRoleAsync()AddClaimAsync()),我的客户端会出现 CORS 错误(角度应用程序在不同的服务器上运行)

但是,如果我使用我的自定义方法注册用户,我不会收到 CORS 错误:

            //Don't get CORS error when commented below
//await _userManager.AddToRoleAsync(user, Constant.User);
//var userClaim = new Claim(Constant.User, user.Email.ToString(), ClaimValueTypes.Integer);
//await _userManager.AddClaimAsync(user, userClaim);

//use custom method
var userObj = _userService.AddNewUser(userInfo);

要为 asp.net、startup.cs 启用 CORS,我正在做:

    public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAllCorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
services.AddMvc();
}


public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
app.UseCors("AllowAllCorsPolicy");
}

我什至尝试在 startup.cs 中手动添加 CORS header ,但没有成功:

public void Configure(IApplicationBuilder app, IHostingEnvironment env,  IServiceProvider serviceProvider)
{
app.Use(async (context, next) =>
{
if (context.Request.Method == "OPTIONS")
context.Response.StatusCode = (int)HttpStatusCode.OK;

var headers = context.Response.Headers;
if (headers.ContainsKey("Access-Control-Allow-Origin"))
{
headers["Access-Control-Allow-Origin"] = string.Join(",", context.Request.Headers["Referer"].Select(x => x.Substring(0, x.Length - 1)));
}
else
{
context.Response.Headers.Append("Access-Control-Allow-Origin", string.Join(",", context.Request.Headers["Referer"].Select(x => x.Substring(0, x.Length - 1))));
}
if (headers.ContainsKey("Access-Control-Allow-Headers"))
{
headers["Access-Control-Allow-Headers"] = "Origin, Content-Type, Accept, Client, Authorization, X-Auth-Token, X-Requested-With";
}
else
{
context.Response.Headers.Append("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Client, Authorization, X-Auth-Token, X-Requested-With");
}
if (headers.ContainsKey("Access-Control-Allow-Methods"))
{
headers["Access-Control-Allow-Credentials"] = "GET, POST, PATCH, PUT, DELETE, OPTIONS";
}
else
{
context.Response.Headers.Append("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
}
if (headers.ContainsKey("Access-Control-Allow-Credentials"))
{
headers["Access-Control-Allow-Credentials"] = "true";
}
else
{
context.Response.Headers.Append("Access-Control-Allow-Credentials", "true");
}
context.Response.Headers.Append("Access-Control-Expose-Headers", "X-Auth-Token");
context.Response.Headers.Append("Vary", "Origin");
await next();
});
}

我看到了this documentation对于 CORS 的 identityserver 选项以及 this CORS文档,但帮助不大。

最佳答案

这适用于较新版本的服务器。

    services.AddSingleton<ICorsPolicyService>((container) => {
var logger = container.GetRequiredService<ILogger<DefaultCorsPolicyService>>();
return new DefaultCorsPolicyService(logger)
{
AllowAll = true
};
});

本次讨论的更多详细信息,感谢原作者

https://github.com/IdentityServer/IdentityServer4/issues/4685

关于c# - 无法在 asp.net core 中为身份服务器 4 启用 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43343672/

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