Skip to content

Instantly share code, notes, and snippets.

@NMillard
Last active August 4, 2022 09:17
Show Gist options
  • Save NMillard/bcd923a1dcedf0e9ad38c9cc541aa2a1 to your computer and use it in GitHub Desktop.
Save NMillard/bcd923a1dcedf0e9ad38c9cc541aa2a1 to your computer and use it in GitHub Desktop.
Validating asymmetric jwt with public key
// ... imports
namespace Authentication.WebClient {
public class Startup {
private readonly IConfiguration configuration;
public Startup(IConfiguration configuration) {
this.configuration = configuration;
}
public void ConfigureServices(IServiceCollection services) {
services.AddControllers();
/*
* Configure validation of JWT signed with a private asymmetric key.
*
* We'll use a public key to validate if the token was signed
* with the corresponding private key.
*/
services.AddSingleton<RsaSecurityKey>(provider => {
// It's required to register the RSA key with depedency injection.
// If you don't do this, the RSA instance will be prematurely disposed.
RSA rsa = RSA.Create();
rsa.ImportRSAPublicKey(
source: Convert.FromBase64String(configuration["Jwt:Asymmetric:PublicKey"]),
bytesRead: out int _
);
return new RsaSecurityKey(rsa);
});
services.AddAuthentication()
.AddJwtBearer("Asymmetric", options => {
SecurityKey rsa = services.BuildServiceProvider().GetRequiredService<RsaSecurityKey>();
options.IncludeErrorDetails = true; // <- great for debugging
// Configure the actual Bearer validation
options.TokenValidationParameters = new TokenValidationParameters {
IssuerSigningKey = rsa,
ValidAudience = "jwt-test",
ValidIssuer = "jwt-test",
RequireSignedTokens = true,
RequireExpirationTime = true, // <- JWTs are required to have "exp" property set
ValidateLifetime = true, // <- the "exp" will be validated
ValidateAudience = true,
ValidateIssuer = true,
};
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
app.UseDeveloperExceptionPage();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization(); // <- allows the use of [Authorize] on controllers and actions
app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); });
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment