Skip to content

Instantly share code, notes, and snippets.

@vmandic
Last active May 17, 2019 12:11
Show Gist options
  • Save vmandic/252769cc147153941aa2a60e264a7ee2 to your computer and use it in GitHub Desktop.
Save vmandic/252769cc147153941aa2a60e264a7ee2 to your computer and use it in GitHub Desktop.
meds-processor, part/4, snippet #14
services.AddScoped<IJwtAuthService, JwtAuthService>();
var tokenOptsConfig = Configuration.GetSection(nameof(AuthTokenOptions).Replace("Options", ""));
var tokenOpts = tokenOptsConfig.Get<AuthTokenOptions>();
services.Configure<AuthTokenOptions>(tokenOptsConfig);
services.AddAuthentication(opts =>
{
opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
opts.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(opts =>
{
opts.RequireHttpsMetadata = true;
opts.SaveToken = true;
opts.ClaimsIssuer = tokenOpts.Issuer;
opts.TokenValidationParameters = new TokenValidationParameters
{
RequireSignedTokens = true,
RequireExpirationTime = true,
IssuerSigningKey = tokenOpts.Key,
ValidIssuer = tokenOpts.Issuer,
ValidAudience = tokenOpts.Audience,
ValidateIssuer = true,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true
};
opts.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment