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 / AppFixture.cs
Last active April 24, 2024 09:58
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 March 5, 2024 05:18
Asymmetric JWT token usage example
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
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; }
}
@dj-nitehawk
dj-nitehawk / CreateTokenEndpoint.cs
Created January 7, 2024 03:13
Standard JWT Authentication Configuration
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
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