首页 > 解决方案 > 使用数据保护 API 存储签名密钥

问题描述

我正在研究 .Net Core Web API,我们使用 Jwt Token 来授权 Web 请求。下面是生成令牌并在启动时配置它的代码。

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateAudience = false,
        ValidateIssuer = false,
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Security:Key"])),
        ValidateLifetime = true,
        ClockSkew = TimeSpan.FromMinutes(5)
    };
});

生成令牌:

private string GenerateToken(string username)
{
    var claims = new[]
    {
        new Claim(ClaimTypes.Name, username),
        new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()),
        new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddDays(1)).ToUnixTimeSeconds().ToString()),
        new Claim(ClaimTypes.Role, "PB"),
        new Claim(ClaimTypes.Version, _configuration["Version"]),
    };

    var token = new JwtSecurityToken(
        new JwtHeader(new SigningCredentials(
            new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Security:Key"])),
            SecurityAlgorithms.HmacSha256)),
        new JwtPayload(claims));

    return new JwtSecurityTokenHandler().WriteToken(token);
}

这按预期工作。最近我们收到一个建议,建议不要使用_configuration["Security:Key"]硬编码的密钥来签署令牌,而是使用数据保护 API。阅读文档后,我有以下问题:

有什么建议么?

我们的目标是摆脱基于配置的密钥并利用 DPAPI。

编辑:

正如@jps 在评论部分提到的那样,在这种情况下,我们必须使用 DPAPI 存储唱歌键。

更新的问题:

我如何达到同样的效果?任何代码示例都会有所帮助。

标签: c#asp.net-corejwtdpapi

解决方案


推荐阅读