c# - 使用数据保护 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。阅读文档后,我有以下问题:
- 如何将 JWT 令牌签名与数据保护 API 结合起来?
- 我是否必须使用 DPAPI 的密钥来签署令牌或使用 DPAPI 的保护和取消保护方法来发送加密的令牌作为响应?
- 我无法找到使用 DPAPI 加密令牌的任何方法。甚至可能吗?
- 从 DPAPI 中提取主密钥/或任何密钥来进行令牌签名是一种好习惯吗?
有什么建议么?
我们的目标是摆脱基于配置的密钥并利用 DPAPI。
编辑:
正如@jps 在评论部分提到的那样,在这种情况下,我们必须使用 DPAPI 存储唱歌键。
更新的问题:
我如何达到同样的效果?任何代码示例都会有所帮助。
解决方案
推荐阅读
- tensorflow - 使用 load_model 时错误调用 keras 内核初始化程序
- android - 允许用户每天标记出勤一次
- kubernetes - kubernetes 在 nfs 上创建空目录
- spring-boot - Springboot @Size对bean属性的约束未触发
- matplotlib - 阈值 Otsu:AttributeError:“AxesSubplot”对象没有属性“ravel”
- c# - SFML 未正确渲染 8 位位图
- php - Laravel whereJsonContains 查询在 5.7 中不起作用
- python - SyntaxError: invalid syntax ,无法对 Pandas 数据框的列执行操作
- awk - 在 Bash 中将带有标题的 csv 转换为 HTML
- php - 无法在 Openshift PHP s2i 基础映像中安装 php-fpm