如何在 ASP.NET Core 6 中加密 jwt 负载?

问题描述 投票:0回答:1

我有这个代码:

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));
}

如何加密令牌中的有效负载数据?也许应该将

TokenDecryptionKey
添加到
options.TokenValidationParameters
,但是我最初如何加密这个令牌?

c# asp.net-core encryption jwt jwe
1个回答
0
投票

在 ASP.NET 6 中,您可以使用

System.IdentityModel.Tokens.Jwt
包加密 JWT 负载,该包提供使用 JSON Web 令牌 (JWT) 的功能。以下是有关如何在 ASP.NET 6 中加密 JWT 负载的分步指南:

  1. System.IdentityModel.Tokens.Jwt
    包添加到您的项目中。您可以通过将以下包引用添加到项目文件中来完成此操作 (
    .csproj
    ):

  2. 在您的代码中,导入必要的命名空间:

    使用 System.IdentityModel.Tokens.Jwt; 使用 System.Security.Cryptography.X509Certificates; 使用 Microsoft.IdentityModel.Tokens;

  3. 加载用于加密的X.509证书。您可以从文件、存储或任何其他来源加载它。这是从文件加载它的示例:

var certificate = new X509Certificate2("path_to_certificate.pfx", "certificate_password");
  1. 创建
    JwtSecurityTokenHandler
    的实例来处理令牌处理:
var tokenHandler = new JwtSecurityTokenHandler();
  1. 创建一个
    TokenValidationParameters
    对象来指定令牌验证参数。将
    IssuerSigningKey
    属性设置为证书的公钥:
var validationParameters = new TokenValidationParameters
{
    IssuerSigningKey = new X509SecurityKey(certificate.PublicKey),
    // Other validation parameters...
};
  1. 使用所需声明创建 JWT 令牌,并使用证书的私钥对其进行加密:
var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(new[]
    {
        new Claim("claim_name", "claim_value"),
        // Add other claims as needed...
    }),
    // Other token descriptor properties...
};

var token = tokenHandler.CreateJwtSecurityToken(tokenDescriptor);
token.EncryptingCredentials = new X509EncryptingCredentials(certificate);

var encryptedToken = tokenHandler.WriteToken(token);
  1. encryptedToken
    现在包含加密的 JWT 有效负载。

记住适当处理异常和错误情况,并根据您的具体要求自定义代码。

请注意,此代码假定您拥有要用于加密的 X.509 证书。您需要获取或创建证书,并确保您有权访问其私钥以进行加密。

我希望这可以帮助您在 ASP.NET 6 中加密 JWT 有效负载!如果您还有任何疑问,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.