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);
}
Now if I use above identity server methods (AddToRoleAsync() and AddClaimAsync()) I get CORS error in my client (angular app running on different server)
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);
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");
}
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();
});
}
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