CORS is not working in web api with OWIN authentication

前端 未结 5 598
花落未央
花落未央 2020-12-05 00:36

In my application i am using web api with token based authentication with CORS support, but when client request for the token, an error occured due to CORS (Cross-Origin Re

5条回答
  •  独厮守ぢ
    2020-12-05 01:16

    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.

提交回复
热议问题