Skip to content

Instantly share code, notes, and snippets.

@vaygeth89
Created November 17, 2020 20:26
Show Gist options
  • Save vaygeth89/f45882f7cca7466aeea09a4bed85e53c to your computer and use it in GitHub Desktop.
Save vaygeth89/f45882f7cca7466aeea09a4bed85e53c to your computer and use it in GitHub Desktop.
tutorial-dotnet-JWTProtectedAPI setUpBearerJwtAuth()
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