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
Created June 4, 2024 04:18
Sending custom response on JWT Bearer Auth failure
var bld = WebApplication.CreateBuilder(args);
bld.Services
.AddAuthenticationJwtBearer(
s => s.SigningKey = "...",
o =>
{
o.Events = new()
{
OnChallenge =
async ctx =>
@dj-nitehawk
dj-nitehawk / MyDbContext.cs
Last active June 6, 2024 09:02
Middleware setup for MS Identity API Endpoints
public class MyDbContext(DbContextOptions<MyDbContext> opts) : IdentityDbContext<IdentityUser>(opts);
@dj-nitehawk
dj-nitehawk / AppFixture.cs
Last active May 2, 2024 06:43
Integration testing with TestContainers & AppFixture
using Testcontainers.MongoDb;
public class Sut : AppFixture<Program>
{
const string Database = "TestingDB";
const string RootUsername = "root";
const string RootPassword = "password";
MongoDbContainer _container = null!;
@dj-nitehawk
dj-nitehawk / Index.html
Created March 24, 2024 02:07
Streaming JSON response with `IAsyncEnumerable`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Streaming Response Viewer</title>
<script>
async function streamResponse(url) {
const response = await fetch(url);
const reader = response.body.getReader();
@dj-nitehawk
dj-nitehawk / Program.cs
Last active May 19, 2024 03:47
Asymmetric JWT token usage example
bld.Services.AddAuthenticationJwtBearer(
s =>
{
s.SigningKey = "base64 encoded 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
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
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.
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
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.
[
JsonPolymorphic(TypeDiscriminatorPropertyName = "_t"),
JsonDerivedType(typeof(MultiChoiceQuestionRequest), "mcq"),
JsonDerivedType(typeof(RatingQuestionRequest), "rq")
]
public class BaseQuestionRequest
{
public int Id { get; set; }
}