OWIN token authentication 400 Bad Request on OPTIONS from browser OWIN token authentication 400 Bad Request on OPTIONS from browser angularjs angularjs

OWIN token authentication 400 Bad Request on OPTIONS from browser


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.


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.