好的,我已经为我的dot net core 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错误(在不同服务器上运行的角度应用程序)< / p>
但是,如果我使用自定义方法注册用户,我不会收到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启用CORS,我正在做startup.cs:
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标头,但没有运气:
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的身份服务器选项以及this CORS文档,但没有多大帮助。
答案 0 :(得分:3)
这适用于服务器的新版本。
services.AddSingleton<ICorsPolicyService>((container) => {
var logger = container.GetRequiredService<ILogger<DefaultCorsPolicyService>>();
return new DefaultCorsPolicyService(logger)
{
AllowAll = true
};
});
在此讨论中有更多详细信息,这要归功于原始作者
https://github.com/IdentityServer/IdentityServer4/issues/4685
答案 1 :(得分:0)
如果将IdentityServer 4与客户端一起使用以进行身份验证,则必须使用IdentityServer 4配置CORS,请参见:IdentityServer4CORS
IdentityServer4 CORS仅用于令牌端点。 您所做的是为所有控制器/方法配置了CORS,这在您的情况下可能是正确的。但是,如果未在Identityserver4上启用CORS,则将无法检索令牌。
您可以将一列允许的CORS添加到您的客户端中,该列表将被添加到Identityserver数据库中,或者添加一个像这样的全局默认值:
var cors = new DefaultCorsPolicyService(_loggerFactory.CreateLogger<DefaultCorsPolicyService>())
{
AllowedOrigins = { "https://foo", "https://bar" }
};
services.AddSingleton<ICorsPolicyService>(cors);
请注意,您也可以将其手动添加到数据库中。