I'm new in JWT authentification, so maybe what i want to do is wrong.
I'm using asymmetric RSA key pair to sign and validate JWT.
In my startup.cs I've :
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,
};
});
}
To generate my token I've in my controller :
[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
});
}
As you see it, my public key is stored in my appsettings. I would like to use options.MetadataAddress so that my client can download metadata about my api and retrieve public key to validate token.
My question is :
It is possible to create a custom .well-known/openid-configuration in .net core ? Or I must to use IdentityServer for example ?
Thanks for help