Noorshx.Auth
1.0.0
dotnet add package Noorshx.Auth --version 1.0.0
NuGet\Install-Package Noorshx.Auth -Version 1.0.0
<PackageReference Include="Noorshx.Auth" Version="1.0.0" />
<PackageVersion Include="Noorshx.Auth" Version="1.0.0" />
<PackageReference Include="Noorshx.Auth" />
paket add Noorshx.Auth --version 1.0.0
#r "nuget: Noorshx.Auth, 1.0.0"
#:package Noorshx.Auth@1.0.0
#addin nuget:?package=Noorshx.Auth&version=1.0.0
#tool nuget:?package=Noorshx.Auth&version=1.0.0
Noorshx.Auth.Authentik
A light-weight, senior-architect level, configuration-first Authentik OAuth2/OIDC authentication library for .NET 9.0.
Designed for high-performance, security-first applications with built-in caching, logging, and production best practices.
Features
✅ One-line setup - builder.Services.AddAuthentik();
✅ 9 authorization attributes - Scope, Group, Role, Claim, Permission-based auth
✅ Production Ready - Built-in caching for policies and introspection results
✅ Security First - Strict introspection for critical endpoints ([ForceIntrospection])
✅ Observability - Structured logging for all authorization decisions
✅ Developer Experience - ICurrentUser service, Swagger helpers, Mock authentication
✅ Microservices Ready - Token forwarding handler & M2M client support
✅ Dynamic - Policies created on-the-fly with 0 configuration overhead
Installation
dotnet add package Noorshx.Auth.Authentik
Production Readiness
This library follows strict security best practices:
- JWT Validation: Primary stateless validation for speed.
- Introspection: Only used when
[ForceIntrospection]is applied (critical ops). - Caching:
- Authorization policies are cached to prevent allocation churn.
- Introspection results are cached for 60s (configurable).
- Fail Secure: Denies access by default if token is invalid or missing.
- Logging: Detailed debug logs for auth failures, suitable for SIEM ingestion.
Advanced Features
1. Current User Service
Inject ICurrentUser to access claims without magic strings.
public class MyController : ControllerBase
{
private readonly ICurrentUser _user;
public MyController(ICurrentUser user) => _user = user;
[HttpGet]
public IActionResult Get()
{
return Ok(new { _user.Id, _user.Email, _user.TenantId });
}
}
2. Swagger Integration
One line to add restrictions and "Authorize" button to Swagger.
builder.Services.AddSwaggerGen(options =>
{
options.AddAuthentikSwagger(builder.Configuration["Authentik:Authority"]);
});
3. Service-to-Service Token Forwarding
Automatically forward the current user's token to downstream services.
services.AddHttpClient("OrderService")
.AddUserAccessTokenHandler();
4. Machine-to-Machine Tokens
Easily get a system token (Client Credentials flow) for background jobs.
public class MyBackgroundService : BackgroundService
{
private readonly ITokenClient _tokenClient;
// ...
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var token = await _tokenClient.GetSystemTokenAsync();
// Use token...
}
}
Configuration Reference
Mock Mode (Local Development)
Bypass Authentik and simulate a logged-in user.
"Authentik": {
"Authority": "https://authentik.example.com",
"ClientId": "my-app",
"Features": {
"UseMockAuth": true
}
}
Problem Details
Authentication errors (401/403) return standard RFC 7807 JSON details automatically.
Quick Start
1. Configure appsettings.json
{
"Authentik": {
"Authority": "https://authentik.yourdomain.com",
"ClientId": "your-client-id",
"ClientSecret": "your-client-secret-if-confidential"
}
}
2. Add to Program.cs
using Noorshx.Auth.Authentik;
var builder = WebApplication.CreateBuilder(args);
// Single line - auto-loads from appsettings.json
builder.Services.AddAuthentik();
builder.Services.AddControllers();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
3. Use attributes in controllers
using Noorshx.Auth.Authentik.Attributes;
[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
[HttpGet]
[RequireScope("read:orders")]
public IActionResult GetOrders() => Ok(new[] { "Order1", "Order2" });
[HttpPost]
[RequireAllScopes("read:orders", "write:orders")]
public IActionResult CreateOrder() => Ok();
[HttpDelete("{id}")]
[RequireAnyScope("delete:orders", "admin:system")]
[ForceIntrospection] // Force token validation for critical operations
public IActionResult DeleteOrder(int id) => Ok();
}
Authorization Attributes
Scope-based
[RequireScope("read:orders")] // Single scope
[RequireAnyScope("read:orders", "admin")] // At least one
[RequireAllScopes("read", "write")] // All required
Group-based
[RequireGroup("Administrators")] // Single group
[RequireAnyGroup("Administrators", "Managers")] // At least one
Role-based
[RequireRole("Admin")] // Simple role check
Claim-based
[RequireClaim("email_verified")] // Check claim exists
[RequireClaim("department", "Engineering")] // Check claim value
Permission-based
[RequirePermission("orders.delete")]
[RequirePermission("payments.process", RequireGroup = "Finance")]
Force Introspection
[ForceIntrospection] // Always validate token with Authentik server
Advanced Configuration
builder.Services.AddAuthentik(options =>
{
options.Authority = "https://authentik.example.com";
options.ClientId = "my-app";
// Token validation
options.Security.TokenValidation.ValidateIssuer = true;
options.Security.TokenValidation.ClockSkew = 60;
// Token introspection
options.Security.Introspection.Enabled = true;
options.Security.Introspection.Probability = 0.1; // 10% of requests
options.Security.Introspection.ForceOnCritical = true;
// Features
options.Features.SessionManagement = true;
options.Features.ServiceToService = false;
});
Configuration Schema
| Property | Type | Default | Description |
|---|---|---|---|
Authority |
string | - | Authentik server URL (required) |
ClientId |
string | - | OAuth2 Client ID (required) |
ClientSecret |
string? | null | Client secret (confidential clients) |
Security.TokenValidation.ValidateIssuer |
bool | true | Validate token issuer |
Security.TokenValidation.ValidateAudience |
bool | true | Validate token audience |
Security.TokenValidation.ValidateLifetime |
bool | true | Validate token expiration |
Security.TokenValidation.ClockSkew |
int | 60 | Clock skew tolerance (seconds) |
Security.Introspection.Enabled |
bool | false | Enable token introspection |
Security.Introspection.Probability |
double | 0.1 | Introspection probability (0.0-1.0) |
Security.Introspection.ForceOnCritical |
bool | true | Force on [ForceIntrospection] endpoints |
Security.Introspection.CacheDuration |
int | 60 | Cache introspection results (seconds) |
Features.SessionManagement |
bool | true | Enable session management |
Features.ServiceToService |
bool | false | Enable service-to-service auth |
Examples
Multiple Scopes (AND logic)
[RequireAllScopes("read:orders", "write:orders", "delete:orders")]
public IActionResult ManageOrders() => Ok();
Multiple Scopes (OR logic)
[RequireAnyScope("support:tier1", "support:tier2", "admin:support")]
public IActionResult SupportDashboard() => Ok();
Combining Attributes
[RequireGroup("Administrators")]
[RequireScope("admin:system")]
[ForceIntrospection]
public IActionResult CriticalAdminOperation() => Ok();
Group + Claim
[RequireGroup("Engineering")]
[RequireClaim("email_verified", "true")]
public IActionResult EngineeringPortal() => Ok();
Migration from Manual Setup
Before (~80 lines):
// Manual JWT configuration
// Policy registration
// Handler registration
// Middleware setup
After (1 line):
builder.Services.AddAuthentik();
Code Reduction: 95%+
License
MIT
Support
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net9.0
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 9.0.0)
- Microsoft.Extensions.Caching.Memory (>= 9.0.0)
- Microsoft.Extensions.Http (>= 9.0.0)
- Swashbuckle.AspNetCore.SwaggerGen (>= 6.5.0)
- System.IdentityModel.Tokens.Jwt (>= 8.2.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.0.0 | 154 | 1/2/2026 |