C# 从自定义标头检索访问令牌
在我的Web API中,我希望从请求中的Cookie头获取访问令牌,然后对令牌进行验证。目前,IdentityServer3.AccessTokenValidation包用于验证承载令牌,它仅从授权头查找令牌。我更愿意继续使用相同的承载令牌验证过程,但是从Cookies头获取令牌,这听起来用方便的代码可行吗?谢谢只需实现您自己的C# 从自定义标头检索访问令牌,c#,http-headers,asp.net-web-api2,access-token,identityserver3,C#,Http Headers,Asp.net Web Api2,Access Token,Identityserver3,在我的Web API中,我希望从请求中的Cookie头获取访问令牌,然后对令牌进行验证。目前,IdentityServer3.AccessTokenValidation包用于验证承载令牌,它仅从授权头查找令牌。我更愿意继续使用相同的承载令牌验证过程,但是从Cookies头获取令牌,这听起来用方便的代码可行吗?谢谢只需实现您自己的TokenProvider,并将其提供给AccessTokenValidationMiddleware: public class MyCustomTokenProvid
TokenProvider
,并将其提供给AccessTokenValidationMiddleware
:
public class MyCustomTokenProvider : IOAuthBearerAuthenticationProvider
{
public Task RequestToken(OAuthRequestTokenContext context)
{
if (context.Token == null)
{
//try get from cookie
var tokenCookie = context.Request.Cookies["myCookieName"];
if (tokenCookie != null)
{
context.Token = tokenCookie;
}
}
return Task.FromResult(0);
}
public Task ValidateIdentity(OAuthValidateIdentityContext context)
{
throw new NotImplementedException();
}
public Task ApplyChallenge(OAuthChallengeContext context)
{
throw new NotImplementedException();
}
}
在Startup.cs
中:
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "http://myhost",
RequiredScopes = new[] { "my-scope" },
TokenProvider = new MyCustomTokenProvider()
});
谢谢费德里科!这也是我的想法,但我误解了RequestToken方法,认为它用于从令牌端点请求新令牌。这很有帮助!