I have this code:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = AuthOptions.ISSUER,
ValidateAudience = true,
ValidAudience = AuthOptions.AUDIENCE,
ValidateLifetime = true,
IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(),
ValidateIssuerSigningKey = true,
};
});
app.Map("/login/{username}", (string username) =>
{
var claims = new List<Claim> {new Claim(ClaimTypes.Name, username) };
var jwt = new JwtSecurityToken(
issuer: AuthOptions.ISSUER,
audience: AuthOptions.AUDIENCE,
claims: claims,
expires: DateTime.UtcNow.Add(TimeSpan.FromMinutes(2)),
signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
return new JwtSecurityTokenHandler().WriteToken(jwt);
});
public class AuthOptions
{
public const string ISSUER = "MyAuthServer";
public const string AUDIENCE = "MyAuthClient";
const string KEY = "mysupersecret_secretsecretsecretkey!123";
public static SymmetricSecurityKey GetSymmetricSecurityKey() =>
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(KEY));
}
How do I encrypt the payload data in my token? Perhaps TokenDecryptionKey should be added to options.TokenValidationParameters, but how do I encrypt this token initially?
This is how you can encrypt the payload in a token, so that you don't see it jwt.io but at the same time, you could get data from the payload in the code:
Program.cs:
Controller or another place: