无法验证 UseJwtBearerAuthentication 中的令牌。授权被拒绝

2024-01-02

使用单个 asp.net(4.6.1) Web 项目,显然我无法验证同一服务器上生成的 jwt 令牌。
启动.cs:

        var secret = Encoding.UTF8.GetBytes("12341234123412341234");
        var jwtFormatter = new CustomJwtFormat("Any", "local", secret);

        // This part checks the tokens
        app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
            AuthenticationMode = AuthenticationMode.Active, // Block requests
            AllowedAudiences = new []{"Any"},
            TokenValidationParameters = new TokenValidationParameters
            {
                IssuerSigningKey = new InMemorySymmetricSecurityKey(secret),
                ValidAudience = "Any",
                ValidIssuer = "local"
            }
        });
        
        // This part issues tokens
        app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
        {
            AllowInsecureHttp = false,
            TokenEndpointPath = new PathString("/auth"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
            Provider = new CustomOAuthProvider(),
            AccessTokenFormat = jwtFormatter,
            RefreshTokenFormat = jwtFormatter
            
        });

        app.UseWebApi(config);

生成令牌的类看起来像

public class CustomJwtFormat : ISecureDataFormat<AuthenticationTicket>
{
    private readonly string _allowedAudience;
    private readonly string _issuer;
    private readonly byte[] _jwtTokenSignKey;

    public CustomJwtFormat(string allowedAudience, string issuer, byte[] jwtTokenSignKey)
    {
        _allowedAudience = allowedAudience;
        _issuer = issuer;
        _jwtTokenSignKey = jwtTokenSignKey;
    }

    public string Protect(AuthenticationTicket data)
    {
        if (data == null) throw new ArgumentNullException(nameof(data));
        
        var signingCredentials = new SigningCredentials
        (
            new InMemorySymmetricSecurityKey(_jwtTokenSignKey),
            "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
            "http://www.w3.org/2001/04/xmlenc#sha256"
        );

        return new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(
            _issuer, 
            _allowedAudience, 
            data.Identity.Claims, 
            DateTime.UtcNow, DateTime.UtcNow.AddMinutes(10), 
            signingCredentials
        ));
        
    }

    public AuthenticationTicket Unprotect(string protectedText)
    {
        throw new NotImplementedException();
    }
}

The tokens I receive from /auth look valid and pass the debugger on jwt.io (without marking base64 for signature) image

However UseJwtBearerAuthentication refuses to validate the token. image

可能的原因是什么?

此外,我尝试手动验证控制器中的相同令牌,而无需[Authorize]它会完美地验证:

        var t = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJpc3MiOiJsb2NhbCIsImF1ZCI6IkFueSIsImV4cCI6MTQ3MjkxMDcwMSwibmJmIjoxNDcyOTEwMTAxfQ.ipSrRSGmje7wfzERsd-M1IDFJnN99AIC4Hs7YX4FIeI";
        var TokenHandler = new JwtSecurityTokenHandler();;
        var key = Encoding.UTF8.GetBytes("12341234123412341234");
        SecurityToken validatedToken;
        TokenValidationParameters paras = new TokenValidationParameters()
        {
            IssuerSigningKey = new InMemorySymmetricSecurityKey(key),
            ValidAudience = "Any",
            ValidIssuer = "local"
        };
        TokenHandler.ValidateToken(t, paras, out validatedToken);

欧文3.0.1.0 系统.IdentityModel.Tokens.Jwt 4.0.3.308261200


问题不在于令牌验证,而在于声明未传递给Thread.CurrentPrincipal认为[Authorize]属性正在读取。

在 webapi 配置中:

config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(DefaultAuthenticationTypes.ExternalBearer));

在启动配置中:

app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
    ...
});

app.UseJwtBearerAuthentication1(new JwtBearerAuthenticationOptions()
{
    AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
    ..
});

In GrantResourceOwnerCredentialsOAuthAuthorizationServerProvider 的:
使用相同的身份验证类型,您可以从中读取context.Options

var identity = new ClaimsIdentity(youClaimsList, context.Options.AuthenticationType);
context.Validated(identity);

并确保一切four位置与 AuthenticationType 具有相同的字符串。 如果HostAuthenticationFilter会有不一样的authenticationType作为输入,它不会将声明从 owin 传递到 webapi。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法验证 UseJwtBearerAuthentication 中的令牌。授权被拒绝 的相关文章

随机推荐