Jwt无法授予有效的发行人或受众群体

时间:2018-10-10 10:54:20

标签: c# asp.net asp.net-core asp.net-core-mvc jwt

这是我的令牌解码器。当我尝试对其进行解码时,我的主体最终为空,从而导致此错误:

  

'IDX10208:无法验证受众。   validationParameters.ValidAudience为null或空白,并且   validationParameters.ValidAudiences为空。'

当我解码令牌以进行检查

  

“ nbf”:1539167980,“ exp”:1539168580,“ iat”:1539167980,“ iss”:   “ http://localhost:55260”,“ aud”:“ http://localhost:55260

这也是我的令牌生成器在其上运行的主机。为什么委托人会引起问题?

public class DecodeToken
{
    private IConfiguration configuration;
    public DecodeToken(IConfiguration configuration)
    {
        this.configuration = configuration;
    }

    public AuthenticationDto Decode(String Input)
    {
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtAuthentication:SecurityKey"]));
        var handler = new JwtSecurityTokenHandler();
        var tokenSecure = handler.ReadToken(Input) as SecurityToken;
        var validations = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = key,
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = false
        };
        SecurityToken securityToken;
        var principal = handler.ValidateToken(Input, validations, out securityToken);
        var jwtSecurityToken = securityToken as JwtSecurityToken;
        if (jwtSecurityToken == null || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))
        {
            throw new SecurityTokenException("Invalid Token");
        }
        AuthenticationDto authenticationDto = new AuthenticationDto
        {
            Email = principal.Claims.Where(c => c.Type == "Email").Select(c => c.Value).SingleOrDefault(),
            UserName = principal.Claims.Where(c => c.Type == "UserName").Select(c => c.Value).SingleOrDefault(),
            FirstName = principal.Claims.Where(c => c.Type == "FirstName").Select(c => c.Value).SingleOrDefault(),
            LastName = principal.Claims.Where(c => c.Type == "LastName").Select(c => c.Value).SingleOrDefault(),
            PhoneNumber = principal.Claims.Where(c => c.Type == "PhoneNumber").Select(c => c.Value).SingleOrDefault(),
            Id = principal.Claims.Where(c => c.Type == "Id").Select(c => c.Value).SingleOrDefault(),
            ExpiryDateTime = principal.Claims.Where(c => c.Type == "exp").Select(c => c.Value).SingleOrDefault(),
            Roles = principal.Claims.Where(c => c.Type == "Roles").Select(c => c.Value).ToList(),
        };
        return authenticationDto;
    }
}

这是我的Startup.cs的样子:

services.AddAuthentication(options => {
    options.DefaultAuthenticateScheme = "Jwt";
    options.DefaultChallengeScheme = "Jwt";
})
.AddJwtBearer("Jwt", options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtAuthentication:SecurityKey"])),

        ValidateIssuer = true,
        ValidIssuer = Configuration["JwtAuthentication:Issuer"],

        ValidateAudience = true,
        ValidAudience = Configuration["JwtAuthentication:Audience"],

        ValidateLifetime = true, //validate the expiration and not before values in the token

        ClockSkew = TimeSpan.Zero //5 minute tolerance for the expiration date
    };
    options.Events = new JwtBearerEvents
    {
        OnAuthenticationFailed = context =>
        {
            if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
            {
                context.Response.Headers.Add("Token-Expired", "true");
            }
            return Task.CompletedTask;
        }
    };
});

我配置错了吗?

1 个答案:

答案 0 :(得分:3)

您的错误似乎很合理。在ConfigureServices中,您要设置TokenValidationParameters,以便它验证您的发行人/受众,并为ValidIssuerValidAudience提供值,但是您<在您的Decode函数中,em>并没有做同样的事情,在此函数中,您仅设置ValidateIssuerValidateAudience而未设置期望的值。您需要在validations中的Decode变量上进行配置,如下所示:

var validations = new TokenValidationParameters
{
    ValidateIssuerSigningKey = true,
    IssuerSigningKey = key,
    ValidateIssuer = true,
    ValidateAudience = true,
    ValidateLifetime = false,
    // Add these...
    ValidIssuer = configuration["JwtAuthentication:Issuer"],
    ValidAudience = configuration["JwtAuthentication:Audience"]
};