1

I tried solutions I found here in stackoverflow and other sites, but they did not solve my issue.

So what I did first is to install the Owin.Cors package and remove the AspNet.WebApi.Cors to see it that the only thing I need to enable CORS to our Web Api and OAuth. It does work in OAuth but not in the Web Api. As the suggestion that to make it work it should be initiliaze first before any configuration so I did this, see the below code.

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

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/account/login"),
        Provider = new CookieAuthenticationProvider
        {
            // remove for brevity
        },
        ExpireTimeSpan = TimeSpan.FromMinutes(Settings.Instance.SessionExpiryTimeout)
    });

    DataProtectionProvider = app.GetDataProtectionProvider();

    app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

    app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
    {
        // remove content for brevity
    });

    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}

When I'm doing a request to retrieve a token I'm getting this:

"Access-Control-Allow-Origin": "*" 
"Access-Control-Allow-Credentials": "true"

However when I'm calling to an Api and I assume that the response header would include the above but it didn't. Thus cause an exception: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:44320' is therefore not allowed access. The response had HTTP status code 404.

I also tried to add again the AspNet.WebApi.Cors but this does not work. Would it be because of our configuration, we are using Autofac. See the below code:

WebApiConfig

public class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute("*", "*", "GET,POST");
        config.EnableCors(cors);

        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        var jsonpFormatter = new JsonpMediaTypeFormatter(config.Formatters.JsonFormatter);
        config.Formatters.Add(jsonpFormatter);

        config.Routes.MapHttpRoute(
            "ApiDefault",
            "api/{controller}/{id}",
            new {id = RouteParameter.Optional}
        );

    } 
}

DependencyConfig

public class DependencyConfig
{
    public static void Register()
    {
        var builder = new ContainerBuilder();

        builder.RegisterControllers(Assembly.GetExecutingAssembly());
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

        // omitted some codes

        var container = builder.Build();

        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
    }
}

Global.asax

protected void Application_Start()
{
    XmlConfigurator.Configure();

    MvcHandler.DisableMvcResponseHeader = true;

    // omitted some codes

    WebApiConfig.Register(GlobalConfiguration.Configuration);

    // omitted some codes

    DependencyConfig.Register();
    JsonConfig.Configure();
}

Any idea what causing the problem? Thank you.

rpmansion
  • 1,964
  • 1
  • 9
  • 26
  • _var cors = new EnableCorsAttribute("*", "*", "GET,POST");_ may be you should add _OPTIONS_ verb as well as a pre-flight request will be made for requests with custom headers (or in MDN terms, non-simple request https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS) – Developer Apr 20 '17 at 05:18
  • you can use this question http://stackoverflow.com/questions/27218240/cors-in-asp-net-mvc5 – M.h Basiri Apr 20 '17 at 06:55
  • Can you please try parameterless EnableCors() in WebAPIConfig without EnableCorsAttribute and then enable it at action level or controller level? – Rohit Garg Apr 20 '17 at 07:01
  • @RohitGarg I tried that but it did not work. – rpmansion Apr 20 '17 at 07:15
  • Ok. Which webapi version is it? And any luck putting hostname in EnableCorsAttribute? – Rohit Garg Apr 20 '17 at 07:57
  • @RohitGarg Microsoft.AspNet.WebApi - v.5.2.0 – rpmansion Apr 21 '17 at 06:03
  • @Developer I did try adding the `OPTIONS` but did not work. – rpmansion Apr 21 '17 at 06:04
  • @rpmansion - You should probably check the network tab to see which request is actually failing. The error message says - _The response had HTTP status code 404_ which I think the route you requested is invalid and hence throwing _Not Found_ error. Also try giving `*` just in case `var cors = new EnableCorsAttribute("*", "*", "*");` – Developer Apr 21 '17 at 06:35
  • I'm using now the `*` and doing some testing, lets see. I also notice this on our web.config. ` ` – rpmansion Apr 21 '17 at 07:08

0 Answers0