Last active
November 13, 2020 20:02
-
-
Save NMillard/a32cf9c80fd0ed0834cda502c5534bbb to your computer and use it in GitHub Desktop.
Configuring Startup to use JWT authorization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ... 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