带有WebApi .NET核心的JwtSecurity令牌异常IDX10603

时间:2019-06-20 16:11:32

标签: c# asp.net-core

我有一个WebApi项目,该项目在Windows上运行良好,当我尝试生成令牌但我总是遇到此异常时,我切换到了VS for macOS的MacOS。

  

System.ArgumentOutOfRangeException:IDX10603:解密失败。尝试过的键:“ [PII隐藏]”。   捕获的异常:    '[PII隐藏]。   令牌:“ [PII隐藏]”   参数名称:KeySize

我发现了相同的问题Here,问题是SecretKey的大小需要大于或等于128位。我的秘密密钥更大f45fd5sd4f54s5r4s5d4f5s4vdrt7e69y8rtntyu*&%*&(%(&*%(sdokgfópdfjgopdsrjfgposbmeutv-0e5y-5derftgedr6tyrt67rty56hje56dr6yu6, 但仍然存在相同的问题。

生成令牌的类:

public class JWT
{
    private List<Claim> Claim = new List<Claim>();
    public string GetUserToken(string tp,string id)
    {
        var sck = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")));
        var sc = new SigningCredentials(sck, SecurityAlgorithms.HmacSha256Signature);

        if(tp == "Host")
        {
            Claim.Add(new Claim(ClaimTypes.Role, "Host"));
            Claim.Add(new Claim(ClaimTypes.Name, id));
        }
        else
        {
            Claim.Add(new Claim(ClaimTypes.Role, "Client"));
            Claim.Add(new Claim(ClaimTypes.Name, id));
        }

        var token = new JwtSecurityToken(         

            expires: DateTime.Now.AddDays(30),
            signingCredentials: sc,
            claims: Claim
            );
        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}

启动

public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        var SymmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")));
        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(x => {
            x.RequireHttpsMetadata = false;
            x.SaveToken = true;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = SymmetricSecurityKey,
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());
        app.UseAuthentication();
        app.UseHttpsRedirection();
        app.UseResponseCompression();
        app.UseDeveloperExceptionPage();
        app.UseMvc();

    }

0 个答案:

没有答案