CORS works for access token but not for refresh token in Web Api 2

这一生的挚爱 提交于 2019-12-10 19:17:01

问题


I have a web api 2 app which I call to using an angularjs client. The web api app is capable of issuing access tokens and refresh tokens for authentication.

Having the following lines in the "GrantResourceOwnersCredentials" method, the CORS is working fine for allowing to issue access tokens:

var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");
  if (allowedOrigin == null) allowedOrigin = "*";
  context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

However, when I try to issue refresh tokens through the angularjs app, I get this good old error in the console:

OPTIONS http://localhost:65141/token
(index):1 XMLHttpRequest cannot load http://localhost:65141/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:56815' is therefore not allowed access. The response had HTTP status code 400.

I was wondering as the access tokens are being issued fine, and the refresh tokens are also issued using the same endpoint, what should I do to overcome this issue?

By the way, the angular code is fine. I disabled google chrome web security and then everything worked! Any help is greatly appreciated!


回答1:


After searching the whole freaking internet, here is what I found that resolves the problem. Adding this code to the AuthorizationProvider will resolve the problem:

public override Task MatchEndpoint(OAuthMatchEndpointContext context)
        {
            if (context.IsTokenEndpoint && context.Request.Method == "OPTIONS")
            {
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "authorization" });
                context.RequestCompleted();
                return Task.FromResult(0);
            }

            return base.MatchEndpoint(context);
        }


来源:https://stackoverflow.com/questions/31932286/cors-works-for-access-token-but-not-for-refresh-token-in-web-api-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!