Passing and verifying the OWIN Bearer token in Query String in WebAPI

前端 未结 3 2044
悲&欢浪女
悲&欢浪女 2020-12-31 03:22

Short Version: I need to pass and verify the OWIN bearing token as a query parameter rather than in the request header.

How do I then get the method to authorized ba

相关标签:
3条回答
  • 2020-12-31 03:36

    I wrote about how that works here: http://leastprivilege.com/2013/10/31/retrieving-bearer-tokens-from-alternative-locations-in-katanaowin/

    0 讨论(0)
  • 2020-12-31 03:39

    or do it like this

        app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
        {
            Authority = IdentityConfig.Authority,
            RequiredScopes = new[] { "api" },
            TokenProvider = new OAuthBearerAuthenticationProvider
            {
                OnRequestToken = ctx =>
                {
                    if (String.IsNullOrWhiteSpace(ctx.Token) && ctx.Request.QueryString.HasValue)
                    {
                        NameValueCollection parsedQuery = HttpUtility.ParseQueryString(ctx.Request.QueryString.Value);
                        ctx.Token = parsedQuery["access_token"];
                    }
    
                    return Task.FromResult(0);
                }
            }
        });
    
    0 讨论(0)
  • 2020-12-31 03:42

    For completeness, here's another neat solution.

    Extract:

    app.Use(async (context, next) =>
    {
        if (context.Request.QueryString.HasValue)
        {
            if (string.IsNullOrWhiteSpace(context.Request.Headers.Get("Authorization")))
            {
                var queryString = HttpUtility.ParseQueryString(context.Request.QueryString.Value);
                string token = queryString.Get("access_token");
    
                if (!string.IsNullOrWhiteSpace(token))
                {
                    context.Request.Headers.Add("Authorization", new[] { string.Format("Bearer {0}", token) });
                }
            }
        }
    
        await next.Invoke();
    });
    
    0 讨论(0)
提交回复
热议问题