NIS.Keycloak.Blazor 0.1.1
NIS.Keycloak.Blazor
Production-ready Keycloak authentication integration for Blazor Server applications.
Features
- Flattens Keycloak realm and resource roles from the access token into standard ASP.NET Core
ClaimTypes.Roleclaims - Supports both
[Authorize(Roles = "...")]and policy-based authorization - Provides a debug token view component (development only)
- Includes
ApiAccessTokenHandlerfor forwarding tokens to downstream APIs
Installation
dotnet add package NIS.Keycloak.Blazor
Quick Start
1. Configure appsettings.json
{
"Keycloak": {
"Realm": "TestRealm",
"AuthServerUrl": "https://sso.nis.mv/", //your keycloak server
"SslRequired": "none",
"Resource": "test-blazor-server-0238a4e3-c633-4d00-bd5c-aysd5656hgh",
"VerifyTokenAudience": true,
"EnableRolesMapping": "ResourceAccess",
"Credentials": {
"Secret": "asdgjasdgasgd7asd"
},
"confidentialPort": 0,
"_comment_RequireHttpsMetadata": "Only set to false in local development. Disabling in production exposes to MITM attacks.",
"RequireHttpsMetadata": true
}
}
2. Register services in Program.cs
using NIS.Keycloak.Blazor.Configuration;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddNisKeycloakAuthentication(builder.Configuration);
// Optional: register a named HttpClient that forwards the access token
builder.Services.AddNisKeycloakApiClient(builder.Configuration, "ApiClient");
// Define policies
builder.Services.AddAuthorizationBuilder()
.AddAppPolicy("ViewWeather", "claim:view-weather");
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapNisKeycloakAuthEndpoints();
app.Run();
3. Protect pages
@attribute [Authorize(Roles = "Admin")]
@attribute [Authorize(Policy = "ViewWeather")]
4. Optional: add debug token view
Reference NIS.Keycloak.Blazor.Debug and navigate to /nis-auth-keycloak-token-debug-view.
This page is only available in the Development environment.
Security Notes
- Always set
RequireHttpsMetadatatotruein production. Disabling it exposes the application to man-in-the-middle attacks on OIDC metadata. - The debug token view (
Token.razor) displays raw JWTs and should never be enabled in production.
License
GPL-3.0-only
No packages depend on NIS.Keycloak.Blazor.
.NET 10.0
- Keycloak.AuthServices.Authentication (= 3.0.0-rc.1)