【发布时间】:2022-01-14 12:11:13
【问题描述】:
我是 JWT 身份验证的新手,所以我想做的可能是错误的。
我正在使用非对称 RSA 密钥对来签署和验证 JWT。
在我的 startup.cs 中我有:
public void ConfigureServices(IServiceCollection services) {
services.AddControllers();
services.AddSingleton<RsaSecurityKey>(provider => {
RSA rsa = RSA.Create();
rsa.ImportRSAPublicKey(
source: Convert.FromBase64String(configuration["Jwt:PublicKey"]),
bytesRead: out int _
);
return new RsaSecurityKey(rsa);
});
services.AddAuthentication()
.AddJwtBearer("Asymmetric", options => {
SecurityKey rsa = services.BuildServiceProvider().GetRequiredService<RsaSecurityKey>();
options.TokenValidationParameters = new TokenValidationParameters {
IssuerSigningKey = rsa,
ValidAudience = "audience-test",
ValidIssuer = "test-issuer",
RequireSignedTokens = true,
RequireExpirationTime = true,
ValidateLifetime = true,
ValidateAudience = true,
ValidateIssuer = true,
};
});
}
要生成我在控制器中的令牌:
[HttpPost]
[Route("Asymmetric")]
public IActionResult GenerateTokenAsymmetric()
{
using RSA rsa = RSA.Create();
rsa.ImportRSAPrivateKey(
source: Convert.FromBase64String(_configuration["Jwt:PrivateKey"]),
bytesRead: out int _);
var signingCredentials = new SigningCredentials(
key: new RsaSecurityKey(rsa),
algorithm: SecurityAlgorithms.RsaSha256
);
DateTime jwtDate = DateTime.Now;
var jwt = new JwtSecurityToken(
audience: "test-audience",
issuer: "test-issuer",
claims: new Claim[] { new Claim(ClaimTypes.NameIdentifier, "John") },
notBefore: jwtDate,
expires: jwtDate.AddMinutes(1),
signingCredentials: signingCredentials
);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
return Ok(new
{
jwt = token
});
}
如您所见,我的公钥存储在我的 appsettings 中。 我想使用 options.MetadataAddress 以便我的客户可以下载有关我的 api 的元数据并检索公钥以验证令牌。
我的问题是:
可以在 .net core 中创建自定义 .well-known/openid-configuration 吗?或者我必须使用 IdentityServer 例如?
感谢您的帮助
【问题讨论】:
标签: asp.net-core jwt rsa openid-connect