Skip to content

Instantly share code, notes, and snippets.

@NMillard
Last active November 13, 2020 20:02
Show Gist options
  • Select an option

  • Save NMillard/a32cf9c80fd0ed0834cda502c5534bbb to your computer and use it in GitHub Desktop.

Select an option

Save NMillard/a32cf9c80fd0ed0834cda502c5534bbb to your computer and use it in GitHub Desktop.
Configuring Startup to use JWT authorization
// ... 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 regular JWT signed with a symmetric key
*/
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) // Set default to 'Bearer'
.AddJwtBearer(options => { // Configure how the Bearer token is validated
var symmetricKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:Symmetric:Key"]));
options.IncludeErrorDetails = true; // <- great for debugging
// Configure the actual Bearer validation
options.TokenValidationParameters = new TokenValidationParameters {
IssuerSigningKey = symmetricKey,
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 action
app.UseEndpoints(endpoints => {
endpoints.MapDefaultControllerRoute();
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment