Skip to content

Instantly share code, notes, and snippets.

View dj-nitehawk's full-sized avatar

Dĵ ΝιΓΞΗΛψΚ dj-nitehawk

View GitHub Profile
@dj-nitehawk
dj-nitehawk / Program.cs
Last active March 5, 2024 05:18
Asymmetric JWT token usage example
View Program.cs
bld.Services.AddAuthenticationJwtBearer(
s =>
{
s.SigningKey = "public key";
s.SigningStyle = TokenSigningStyle.Asymmetric;
s.KeyIsPemEncoded = true; // only if public key is in PEM format
},
b =>
{
b.TokenValidationParameters.ValidIssuer = "issuer";
@dj-nitehawk
dj-nitehawk / AuthenticationHandler.cs
Created February 24, 2024 06:45
Basic Authentication With Swagger Support
View AuthenticationHandler.cs
public class BasicAuth(IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder)
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
internal const string SchemeName = "Basic";
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (IsPublicEndpoint() || !Request.Headers.ContainsKey("Authorization"))
@dj-nitehawk
dj-nitehawk / Program.cs
Last active March 3, 2024 07:59
Customizing Swagger Middleware & UI Paths
View Program.cs
app.UseSwaggerGen(
s =>
{
//where to serve swagger.json files from
s.Path = "/PREFIX/swagger/{documentName}/swagger.json";
//api endpoint server base path customization
s.PostProcess = (document, request) =>
{
document.Servers.Clear();
@dj-nitehawk
dj-nitehawk / Program.cs
Created January 21, 2024 05:40
Results pattern with a Post-Processor doing the response sending.
View Program.cs
var bld = WebApplication.CreateBuilder(args);
bld.Services
.AddFastEndpoints()
.SwaggerDocument();
var app = bld.Build();
app.UseFastEndpoints()
.UseSwaggerGen();
app.Run();
@dj-nitehawk
dj-nitehawk / 1-Program.cs
Created January 15, 2024 13:55
Custom Authorization Handler Sample
View 1-Program.cs
var builder = WebApplication.CreateBuilder();
builder.Services.AddTransient<IAuthorizationHandler, TestHandler>(); //Register your handler
builder.Services.AddFastEndpoints();
builder.Services.AddJWTBearerAuth("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
builder.Services.AddAuthorization(o =>
{
//Set the default policy to use your requirements (so you don't have to set the policy on each endpoint)
o.DefaultPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.AddRequirements(new OperationAuthorizationRequirement()) //Using built-in requirement for testing here
@dj-nitehawk
dj-nitehawk / 1-BaseQuestion.cs
Last active January 10, 2024 10:40
Validator inheritance for polymorphic DTOs.
View 1-BaseQuestion.cs
[
JsonPolymorphic(TypeDiscriminatorPropertyName = "_t"),
JsonDerivedType(typeof(MultiChoiceQuestionRequest), "mcq"),
JsonDerivedType(typeof(RatingQuestionRequest), "rq")
]
public class BaseQuestionRequest
{
public int Id { get; set; }
}
@dj-nitehawk
dj-nitehawk / CreateTokenEndpoint.cs
Created January 7, 2024 03:13
Standard JWT Authentication Configuration
View CreateTokenEndpoint.cs
public class CreateToken : EndpointWithoutRequest
{
public override void Configure()
{
Get("token");
AllowAnonymous();
}
public override async Task HandleAsync(CancellationToken ct)
{
@dj-nitehawk
dj-nitehawk / Program.cs
Last active January 23, 2024 04:14
Registration of additional assemblies for type discovery
View Program.cs
bld.Services.AddFastEndpoints(
o => o.Assemblies = new[]
{
typeof(SomeAssemblyName).Assembly,
typeof(AnotherAssemblyName).Assembly
});
//this also enables bypassing the default blacklist of assemblies: https://github.com/FastEndpoints/FastEndpoints/blob/main/Src/Library/Main/EndpointData.cs#L28-L48
@dj-nitehawk
dj-nitehawk / ClaimTransformation.cs
Last active December 9, 2023 07:17
Dynamic claim/permission hydration instead of embedding everything in JWT Token
View ClaimTransformation.cs
sealed class UserPermissionHydrator(UserPermissionService userPermissionService) : IClaimsTransformation
{
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
var userId = principal.Claims.FirstOrDefault(c => c.Type == "UserId")?.Value;
ArgumentNullException.ThrowIfNull(userId);
var userPermissions = await userPermissionService.GetPermissionsForUser(userId);
if (userPermissions.Length != 0)
@dj-nitehawk
dj-nitehawk / Program.cs
Last active October 23, 2023 13:09
Using old style app host-builder with `Startup.cs`
View Program.cs
public class Program
{
public static void Main(string[] args)
=> CreateHostBuilder(args).Build().Run();
public static IHostBuilder CreateHostBuilder(string[] args)
=> Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>());
}