Created
March 2, 2022 20:03
-
-
Save MikeLarned/b5eb7bf793267aa40272aa2ea09f9024 to your computer and use it in GitHub Desktop.
JwtBearerEvents .netcore 6.0
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
using System.IdentityModel.Tokens.Jwt; | |
using Microsoft.AspNetCore.Authentication.JwtBearer; | |
var builder = WebApplication.CreateBuilder(args); | |
// Add services to the container. | |
builder.Services.AddControllers(); | |
builder.Services.AddEndpointsApiExplorer(); | |
builder.Services.AddSwaggerGen(); | |
// Inspect JWT | |
builder.Services.AddAuthentication(options => | |
{ | |
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; | |
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; | |
}).AddJwtBearer(options => | |
{ | |
options.Authority = "YourAuthority"; | |
options.Audience = "YourAud"; | |
options.Events = new JwtBearerEvents | |
{ | |
OnTokenValidated = context => | |
{ | |
var tokenRaw = context.HttpContext.Request.Headers["Authorization"]; | |
var token = context.SecurityToken as JwtSecurityToken; | |
var principal = context.Principal; | |
var ver = token?.Claims?.FirstOrDefault(x => x.Type == "ver")?.Value; | |
if (ver != "1.0") | |
context.Fail($"The Verion is not 1.0."); | |
return Task.CompletedTask; | |
}, | |
OnChallenge = async context => | |
{ | |
// Call this to skip the default logic and avoid using the default response | |
context.HandleResponse(); | |
if (context.AuthenticateFailure != null) | |
{ | |
context.Response.StatusCode = 401; | |
var message = context.AuthenticateFailure.Message; | |
await context.Response.WriteAsync(message); | |
} | |
} | |
}; | |
}); | |
builder.Services.AddAuthorization(options => | |
{ | |
options.AddPolicy("Authenticated", | |
policy => policy | |
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) | |
.RequireAuthenticatedUser()); | |
// Make [Authorize] default to our new policy | |
options.DefaultPolicy = options.GetPolicy("Authenticated"); | |
}); | |
var app = builder.Build(); | |
// Configure the HTTP request pipeline. | |
if (app.Environment.IsDevelopment()) | |
{ | |
app.UseSwagger(); | |
app.UseSwaggerUI(); | |
} | |
app.UseHttpsRedirection(); | |
app.UseAuthorization(); | |
app.MapControllers(); | |
app.Run(); | |
//Install-Package Microsoft.AspNetCore.Authentication.JwtBearer -Version 6.0.2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment