ASP.NET Web Api: How to pass an access token (oAuth 2.0) using URL parameter?

后端 未结 3 826
悲&欢浪女
悲&欢浪女 2020-12-24 07:36

Do you have any idea how I can use, an access_token generated by the default asp.net web api 2 OAuth 2 authorization mechanism, in the url parameters. Currently I am able to

相关标签:
3条回答
  • 2020-12-24 07:47

    Well - I agree that the header is a much better alternative - but there are of course situations where the query string is needed. The OAuth2 spec defines it as well.

    Anyways - this feature is built into the Katana OAuth2 middleware:

    http://leastprivilege.com/2013/10/31/retrieving-bearer-tokens-from-alternative-locations-in-katanaowin/

    public class QueryStringOAuthBearerProvider : OAuthBearerAuthenticationProvider
    {
        readonly string _name;
    
        public QueryStringOAuthBearerProvider(string name)
        {
            _name = name;
        }
    
        public override Task RequestToken(OAuthRequestTokenContext context)
        {
            var value = context.Request.Query.Get(_name);
    
            if (!string.IsNullOrEmpty(value))
            {
                context.Token = value;
            }
    
            return Task.FromResult<object>(null);
        }
    }
    

    And then:

    var options = new JwtBearerAuthenticationOptions
    {
        AllowedAudiences = new[] { audience },
        IssuerSecurityTokenProviders = new[]
            {
                new SymmetricKeyIssuerSecurityTokenProvider(
                    issuer,
                    signingKey)
            },
        Provider = new QueryStringOAuthBearerProvider(“access_token”)
    };
    
    0 讨论(0)
  • 2020-12-24 08:12

    This is a terrible idea because the token is not protected in the query string. It is encrypted in the header with SSL.

    0 讨论(0)
  • 2020-12-24 08:13

    So, go to Global.asax and add this method:

            void Application_BeginRequest(object sender, EventArgs e)
            {
                if (ReferenceEquals(null, HttpContext.Current.Request.Headers["Authorization"]))
                {
                    var token = HttpContext.Current.Request.Params["access_token"];
                    if (!String.IsNullOrEmpty(token))
                    {
                        HttpContext.Current.Request.Headers.Add("Authorization", "Bearer " + token);
                    }
                }
            }
    

    UPDATE: Check out @leastprivilege answer. Much better solution.

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