'Enable CORS for ASP API Token request
I have a project that has both an API and an Area that contains some web forms.
Recently the Token endpoint of the API started throwing CORS errors and I can't figure out why or how to fix it.
I've updated the Startup.Auth.cs file with:app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
Also tried adding config.EnableCors(new EnableCorsAttribute("*", "*", "GET,POST")); to the WebApiConfig.cs file.
Neither of these have added the 'Access-Control-Allow-Origin' header that is needed. (I do get a different error if both of these are implemented at the same time, so I know that is not the issue.)
Is there another location in the project that I need to set to allow CORS requests for an auth token?
Solution 1:[1]
I had to this in ApplicationOAuthProvider.cs/GrantResourceOwnerCredentials to work. The first three lines are for reference point only, "context.OwinContext" line was added to make it work.
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
**context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "http://localhost:24589" });**
Use above if you want to individually configure and allow CORS at different access points. If you want to allow application wide then you may modify ApplicationOAuthProvider.cs/ConfigureAuth like below. Either approach works.
public void ConfigureAuth(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
Solution 2:[2]
After enable CORS in WebApiConfig.cs , you should also config the web.config to also enable CORS . It's work in my application :
<system.webServer>
<!--Enbale CORS-->
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://yourwebsite" />
</customHeaders>
</httpProtocol>
<modules>
...
</modules>
</system.webServer>
Solution 3:[3]
I also struggled and spent around 5 hours, finally I got the solution.
Technology : Asp.net Framework
solution: need to install "Microsoft.Owin.Cors"
And Add the below line into "Startup.Auth.cs/ConfigureAuth()" method
app.UseCors(CorsOptions.AllowAll);
we don't want to add anything in any where, this is sufficient and it is working fine for me.
I got the answer from here: Getting token from web API2 from Angular2 leads to CORS issues or null
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nizar |
| Solution 2 | LiYang |
| Solution 3 | Kona Suresh |
