Skip to content

Instantly share code, notes, and snippets.

@dj-nitehawk
Created January 7, 2024 03:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dj-nitehawk/3155971da1d2c9553ae6bcb00dfa6f4c to your computer and use it in GitHub Desktop.
Save dj-nitehawk/3155971da1d2c9553ae6bcb00dfa6f4c to your computer and use it in GitHub Desktop.
Standard JWT Authentication Configuration
{
"Auth":{
"JwtSecret":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
}
public class CreateToken : EndpointWithoutRequest
{
public override void Configure()
{
Get("token");
AllowAnonymous();
}
public override async Task HandleAsync(CancellationToken ct)
{
var jwtSecret = Config["Auth:JwtSecret"]!;
await SendAsync(JWTBearer.CreateToken(jwtSecret, p => p["UserId"] = "001"));
}
}
var bld = WebApplication.CreateBuilder(args);
bld.Services
.AddAuthentication(
o =>
{
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(
o =>
{
o.TokenValidationParameters = new()
{
ValidateAudience = false,
ValidateIssuer = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(bld.Configuration["Auth:JwtSecret"]!))
};
});
bld.Services
.AddAuthorization()
.AddFastEndpoints()
.SwaggerDocument();
var app = bld.Build();
app.UseAuthentication()
.UseAuthorization()
.UseFastEndpoints()
.UseSwaggerGen();
app.Run();
sealed class Protected : EndpointWithoutRequest
{
public override void Configure()
{
Get("protected");
Claims("UserId");
}
public override async Task HandleAsync(CancellationToken c)
{
var userId = User.FindFirstValue("UserId");
await SendAsync($"You are [{userId}] and is authorized!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment