Quick reference for integrating Keycloak 26.2 realm roles, groups, users, and claims with .NET 9 and Blazor WASM applications.
Includes best practices, concrete examples, and step-by-step Keycloak UI instructions.
- Users: Individual accounts for authentication.
- Groups: Collections of users for bulk role/permission assignment.
- Roles: Permissions/access levels. Prefer realm roles for API and SPA authZ.
- Claims: Key-value pairs in JWT tokens, used by .NET/Blazor for authorization.
- Assign roles to groups, then add users to groups for scalable management.
- Use realm roles for API and SPA authZ.
- Map roles and custom attributes to JWT claims.
- Create realm roles:
SystemAdmin
,Admin
,PaidUser
, etc. - Create groups:
SystemAdmins
,Admins
, etc. - Assign roles to groups:
Groups → Select group → Role Mappings → Assign realm roles - Add users to groups:
Users → Select user → Groups → Join group
- Roles → Select realm role (e.g.,
SystemAdmin
) - Attributes tab: Add attribute (e.g.,
CanCreateWhirledPeas: true
) - Map this with a protocol mapper for custom claim exposure.
Enable [Authorize(Roles="...")]
and .RequireRole(...)
in .NET 9.
- Clients → Select your client (
wiscodev-api
orwiscodev-spa
) - Client Scopes tab → Find/select
<client>-dedicated
(e.g.,wiscodev-api-dedicated
) - Click on
<client>-dedicated
to edit - Mappers tab → Add Mapper
- Choose "By configuration"
- Mapper Settings:
- Mapper Type:
User Realm Role
- Name:
role
- Token Claim Name:
role
- Claim JSON Type:
String
- Add to ID token: ON (for SPA)
- Add to Access token: ON (for API)
- Multivalued: ON
- Mapper Type:
- Save
Repeat for all relevant clients (API, SPA, etc).
"role": [
"SystemAdmin",
"Admin",
"PaidUser",
"Guest"
]
// Protect endpoint by role
app.MapGet("/admin/data", () => Results.Ok("Only SystemAdmins can see this!"))
.RequireAuthorization(policy => policy.RequireRole("SystemAdmin"));
// Or use attribute
[Authorize(Roles = "SystemAdmin")]
public IActionResult AdminPage() { ... }
- Add attribute to role or user in Keycloak.
- Map with a User Attribute protocol mapper.
- Use
.RequireClaim("CanCreateWhirledPeas", "true")
in .NET.
Concept | Keycloak UI Path | .NET Usage | Example Value in JWT |
---|---|---|---|
User | Users → Create/Edit | - | - |
Group | Groups → Add/Edit, Add Users | - | - |
Role | Roles → Add/Edit, Assign to Groups | [Authorize(Roles=...)] |
"role": ["SystemAdmin", ...] |
Attribute | Roles/User → Attributes | .RequireClaim("...") |
"CanCreateWhirledPeas": true |
Role Mapper | Client Scopes → dedicated → Mappers | [Authorize(Roles=...)] |
"role": ["SystemAdmin", ...] |
- Use realm roles for scalable, cross-client authorization.
- Assign roles to groups, add users to groups.
- Map realm roles to a top-level
role
claim (multivalued) via a User Realm Role mapper in the client scope. - .NET’s standard role-based auth works out of the box.
- For custom claims, use User Attribute mappers.