How to encrypt JWT security token?

后端 未结 3 1580
梦如初夏
梦如初夏 2020-12-13 02:54

I need to secure my web-token with signing and encryption. I wrote the next lines of code:

var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescrip         


        
3条回答
  •  生来不讨喜
    2020-12-13 03:47

    Try the following example

    Updated Jul-2019: .NET Core, Asp.net Core

    1.Create JWT

    private string CreateJwt(string sub, string jti, string issuer, string audience)
    {
        var claims = new[]
        {
            new Claim(JwtRegisteredClaimNames.Sub, sub),
            new Claim(JwtRegisteredClaimNames.Jti, jti),
        };
    
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SecretKeySecretKeySecretKeySecretKeySecretKeySecretKeySecretKeyS"));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
        var encryptingCredentials = new EncryptingCredentials(key, JwtConstants.DirectKeyUseAlg, SecurityAlgorithms.Aes256CbcHmacSha512);
    
        var jwtSecurityToken = new JwtSecurityTokenHandler().CreateJwtSecurityToken(
            issuer,
            audience,
            new ClaimsIdentity(claims),
            null,
            expires: DateTime.UtcNow.AddMinutes(5),
            null,
            signingCredentials: creds,
            encryptingCredentials: encryptingCredentials
            );
        var encryptedJWT = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
    
        return encryptedJWT;
    }
    

    2.Add to ConfigureServices(IServiceCollection services) in Startup.cs

        services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
    
            ValidIssuer = (string)Configuration.GetSection("JwtToken").GetValue(typeof(string), "Issuer"),
            ValidAudience = (string)Configuration.GetSection("JwtToken").GetValue(typeof(string), "Audience"),
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SecretKeySecretKeySecretKeySecretKeySecretKeySecretKeySecretKeyS")),
            TokenDecryptionKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SecretKeySecretKeySecretKeySecretKeySecretKeySecretKeySecretKeyS")),
            ClockSkew = TimeSpan.FromMinutes(0),
        };
    });
    

提交回复
热议问题