从自定义 header 中检索访问令牌
Retrieve access token from a customised header
在我的 Web API 中,我想从请求中的 Cookies header 中获取访问令牌,然后对令牌进行验证。目前,IdentityServer3.AccessTokenValidation 包用于验证 Bearer 令牌,它仅从授权 header 中查找令牌。最好我想继续使用相同的不记名令牌验证过程,但是从 Cookies header 获取令牌,用方便的代码听起来可行吗?谢谢
只需实现您自己的 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()
});
在我的 Web API 中,我想从请求中的 Cookies header 中获取访问令牌,然后对令牌进行验证。目前,IdentityServer3.AccessTokenValidation 包用于验证 Bearer 令牌,它仅从授权 header 中查找令牌。最好我想继续使用相同的不记名令牌验证过程,但是从 Cookies header 获取令牌,用方便的代码听起来可行吗?谢谢
只需实现您自己的 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()
});