CORS适用于访问令牌,但不适用于Web Api 2中的刷新令牌

Beh*_*ooz 3 authentication cors access-token angularjs asp.net-web-api2

我有一个Web API 2应用程序,我使用angularjs客户端调用该应用程序。Web API应用程序能够发出访问令牌并刷新令牌以进行身份​​验证。

“ GrantResourceOwnersCredentials”方法中包含以下几行,CORS可以正常工作以允许发布访问令牌:

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

但是,当我尝试通过angularjs应用发布刷新令牌时,在控制台中出现了这个旧错误:

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.
Run Code Online (Sandbox Code Playgroud)

我想知道随着访问令牌的发布正常,刷新令牌也使用相同的端点发布,我该怎么做才能克服这个问题?

顺便说一句,角度代码很好。我禁用了谷歌浏览器网络安全,然后一切正常!任何帮助是极大的赞赏!

Beh*_*ooz 6

搜索了整个互联网之后,这就是我发现的解决问题的方法。将此代码添加到AuthorizationProvider中将解决此问题:

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);
        }
Run Code Online (Sandbox Code Playgroud)