OWIN token authentication 400 Bad Request on OPTIONS from browser

别来无恙 提交于 2019-12-03 05:58:53

I've lost some time on this problem today. Finally i think i've found a solution.

Override method inside your OAuthAuthorizationServerProvider:

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);
}

This appears to do three necessary things:

  • Force auth server to respond to OPTIONS request with 200 (OK) HTTP status,
  • Allow request to come from anywhere by setting Access-Control-Allow-Origin
  • Allows Authorization header to be set on subsequent requests by setting Access-Control-Allow-Headers

After those steps angular finally behaves correctly when requesting token endpoint with OPTIONS method. OK status is returned and it repeats request with POST method to get full token data.

Prakash D Modi

Override this method inside your OAuthAuthorizationServerProvider:

    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

Are you running it locally or are you publishing it to Azure like in the blog article's sample code?

If you're running it on Azure, you can easily fix CORS problems by enabling CORS in the Azure portal:

  1. Click on your App Service in the Azure Portal to enter the management screen.
  2. In the list of management options, scroll down to the 'API' section, where you will find the 'CORS' option. (Alternatively type 'CORS' in the search box).
  3. Enter the allowed origin, or enter '*' to enable all, and click save.

This fixed the OPTIONS preflight check problem for me, which a few other people seem to have had from the code in that particular blog article.

Solved it. The problem was not sending with OPTIONS request header Access-Control-Request-Method

This should do the trick:

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