【问题标题】:Retrieve access token from a customised header从自定义标头中检索访问令牌
【发布时间】:2016-08-27 07:11:50
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    只需实现您自己的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方法,认为它是用来从令牌端点请求新令牌的。这很有帮助!
    猜你喜欢
    • 2017-09-28
    • 1970-01-01
    • 2016-11-23
    • 2018-03-01
    • 1970-01-01
    • 2011-11-18
    • 1970-01-01
    • 2021-09-05
    • 2015-09-08
    相关资源
    最近更新 更多