CORS is not working in web api with OWIN authentication

末鹿安然 提交于 2019-11-28 05:58:32

Be sure you've got only

app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

configured, and not also the old style 'config.EnableCors()' in your Global.asax or WebApiConfig. Furthermore: place the above statement as the first one in your owin Startup class. Yes that really makes a difference, setting it later can also cause cors to not work.

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

        ... etc

OWIN and Microsoft.AspNet.WebApi.Cors are two separate libraries and each one needs separate configuration.

Disable use of CORS with OWIN:

public void Configuration(IAppBuilder app)
{
        //app.UseCors(CorsOptions.AllowAll);

Find GrantResourceOwnerCredentials method and add Access-Control-Allow-Origin to context so when it returns a call after authentication is completed that browser finds the header and accepts it.

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "http://localhost" });

Now install Microsoft.AspNet.WebApi.Cors package from Nuget to your webapi project, and add this to Register method

public static void Register(HttpConfiguration config)
{
        var cors = new EnableCorsAttribute("http://localhost, ", "accept,accesstoken,authorization,cache-control,pragma,content-type,origin", "GET,PUT,POST,DELETE,TRACE,HEAD,OPTIONS");

        config.EnableCors(cors);

This did it for me.

Especially if you are having problem with the Web API bearer token when using CORS then dont forget to put "TOKEN" in the list of your allowed methods.

Please put the code in your system.webServer of web.config, that is how i solved mine

<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE, TOKEN" />
 </customHeaders>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!