OWIN token authentication 400 Bad Request on OPTIONS from browser

后端 未结 5 485
眼角桃花
眼角桃花 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:44

    This should do the trick:

    app.UseCors(CorsOptions.AllowAll);
    
    0 讨论(0)
  • 2021-02-05 16:45

    Override this method inside your OAuthAuthorizationServerProvider:

        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
        }
    
    0 讨论(0)
  • 2021-02-05 16:50

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-05 16:59

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

    0 讨论(0)
提交回复
热议问题