Created
January 7, 2024 03:13
-
-
Save dj-nitehawk/3155971da1d2c9553ae6bcb00dfa6f4c to your computer and use it in GitHub Desktop.
Standard JWT Authentication Configuration
This file contains 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
{ | |
"Auth":{ | |
"JwtSecret":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" | |
} | |
} |
This file contains 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
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")); | |
} | |
} |
This file contains 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
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(); |
This file contains 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
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