Skip to content

Instantly share code, notes, and snippets.

@dj-nitehawk
Created January 15, 2024 13:55
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/d2f585747c0711f92ab7c7923f670e29 to your computer and use it in GitHub Desktop.
Save dj-nitehawk/d2f585747c0711f92ab7c7923f670e29 to your computer and use it in GitHub Desktop.
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
.Build();
//Or if you don't mind setting the policy on each endpoint.
//o.AddPolicy("MyPolicy", b => b.RequireAuthenticatedUser().AddRequirements(new OperationAuthorizationRequirement()).Build());
});
builder.Services.SwaggerDocument();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.UseFastEndpoints();
app.UseSwaggerGen();
app.Run();
public class TestHandler : AuthorizationHandler<OperationAuthorizationRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, OperationAuthorizationRequirement requirement)
{
if (context.User.HasClaim("UserId", "12345"))
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
public class TokenEndpoint : EndpointWithoutRequest
{
public override void Configure()
{
Get("/token");
AllowAnonymous();
}
public override async Task HandleAsync(CancellationToken ct)
{
await SendAsync(
JWTBearer.CreateToken(
signingKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
claims: ("UserId", "001")));
}
}
public class ProtectedEndpoint : EndpointWithoutRequest
{
public override void Configure()
{
Get("/protected");
//Policies("MyPolicy"); //If not setting DefaultPolicy, you need to uncomment this
}
public override async Task HandleAsync(CancellationToken ct)
{
await SendStringAsync("ok! you have permission to see this...");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment