从自定义标头中检索访问令牌

时间:2016-05-02 13:37:54

标签: c# http-headers asp.net-web-api2 access-token identityserver3

在我的Web API中,我想从请求中的Cookies标头获取访问令牌,然后对令牌进行验证。目前,IdentityServer3.AccessTokenValidation包用于验证Bearer令牌,它仅从Authorization标头中查找令牌。我希望继续使用相同的承载令牌验证过程,但从Cookies标头获取令牌,这听起来是否可以使用方便的代码?感谢

1 个答案:

答案 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()
});