Created
November 17, 2020 20:26
-
-
Save vaygeth89/f45882f7cca7466aeea09a4bed85e53c to your computer and use it in GitHub Desktop.
tutorial-dotnet-JWTProtectedAPI setUpBearerJwtAuth()
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
private void setUpBearerJwtAuth(IServiceCollection services) | |
{ | |
//Fetch JWT configuration from appsettings.json | |
var jwtSection = Configuration.GetSection("jwtBearerTokenSettings"); | |
//Parse jwtSection from appsettings.json into Concrete Class "JWTBearerTokenSettings" | |
services.Configure<JWTBearerTokenSettings>(jwtSection); | |
var jwtBearerTokenSettings = jwtSection.Get<JWTBearerTokenSettings>(); | |
var key = Encoding.ASCII.GetBytes(jwtBearerTokenSettings.SecretKey); | |
services.AddAuthentication(options => | |
{ | |
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; | |
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; | |
}) | |
.AddJwtBearer(options => | |
{ | |
options.RequireHttpsMetadata = false; | |
options.SaveToken = true; | |
options.TokenValidationParameters = new TokenValidationParameters() | |
{ | |
ValidateIssuer = true, | |
ValidIssuer = jwtBearerTokenSettings.Issuer, | |
ValidateAudience = true, | |
ValidAudience = jwtBearerTokenSettings.Audience, | |
ValidateIssuerSigningKey = true, | |
IssuerSigningKey = new SymmetricSecurityKey(key), | |
ValidateLifetime = true, | |
ClockSkew = TimeSpan.Zero | |
}; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment