您是否知道如何使用url参数中默认的asp.net web api 2 OAuth 2授权机制生成的access_token。目前,我可以通过发送带有Authorization header 的请求来成功进行授权,如下所示:
Accept: application/json
Content-Type: application/json
Authorization: Bearer pADKsjwMv927u...
我想要的是通过如下所示的URL参数启用授权:
https://www.domain.com/api/MyController?access_token=pADKsjwMv927u...
最佳答案
嗯-我同意 header 是更好的选择-但是在某些情况下当然需要查询字符串。 OAuth2规范也对此进行了定义。
无论如何-Katana OAuth2中间件内置了此功能:
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);
}
}
接着:
var options = new JwtBearerAuthenticationOptions
{
AllowedAudiences = new[] { audience },
IssuerSecurityTokenProviders = new[]
{
new SymmetricKeyIssuerSecurityTokenProvider(
issuer,
signingKey)
},
Provider = new QueryStringOAuthBearerProvider(“access_token”)
};