无法在 asp.net 核心中为身份服务器 4 启用 CORS [英] Not able to enable CORS for identity server 4 in asp.net core
问题描述
好的,我已经为我的 dot net core API 添加了 CORS 策略,但不知何故这些 CORS 策略不适用于身份服务器 4 端点.我有以下 api 尝试注册用户:
Ok, I have added CORS policy for my dot net core APIs but somehow these CORS policies are not working for identity server 4 endpoints. I have following api where I try to register a user:
[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 错误(在不同服务器上运行的 Angular 应用程序)
Now if I use above identity server methods (AddToRoleAsync() and AddClaimAsync()) I get CORS error in my client (angular app running on different server)
但是,如果我使用自定义方法注册用户,则不会出现 CORS 错误:
However if I use my custom method to register the user, I don't get CORS error:
//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我正在做:
To enable CORS for asp.net, startup.cs I am doing:
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 标头,但没有成功:
I even tried to add the CORS headers manually in startup.cs, but no luck:
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();
});
}
我看到了此文档,用于 CORS 和还有 这个 CORS 文档,但没有太大帮助.
I saw this documentation for identityserver Options for CORS and also this CORS documentation but not much helpful.
推荐答案
这适用于较新版本的服务器.
This works for the newer version of the server.
services.AddSingleton<ICorsPolicyService>((container) => {
var logger = container.GetRequiredService<ILogger<DefaultCorsPolicyService>>();
return new DefaultCorsPolicyService(logger)
{
AllowAll = true
};
});
在此讨论中有更多详细信息,感谢原作者
more details here at this discussion, with credit to the original author
https://github.com/IdentityServer/IdentityServer4/issues/4685
这篇关于无法在 asp.net 核心中为身份服务器 4 启用 CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!