在我的Web API中,我想从请求中的Cookies标头获取访问令牌,然后对令牌进行验证。目前,IdentityServer3.AccessTokenValidation包用于验证Bearer令牌,它仅从Authorization标头中查找令牌。我希望继续使用相同的承载令牌验证过程,但从Cookies标头获取令牌,这听起来是否可以使用方便的代码?感谢
答案 0 :(得分:2)
只需实施您自己的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()
});