OWIN token authentication 400 Bad Request on OPTIONS from browser

后端 未结 5 502
眼角桃花
眼角桃花 2021-02-05 16:22

I am using token authentication for small project based on this article: http://bitoftech.net/2014/06/09/angularjs-token-authentication-using-asp-net-web-api-2-owin-asp-net-iden

5条回答
  •  时光说笑
    2021-02-05 16:52

    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.

提交回复
热议问题