Keycloak.AuthServices Documentation

repository·main·Indexed 20 days ago

https://github.com/nikiforovall/keycloak-authorization-services-dotnet

Authentication and authorization integration for .NET applications using Keycloak. Supports JWT, OIDC, UMA 2.0, and provides an SDK for the Keycloak Admin API. Includes specialized NuGet packages for authentication, role-based policies, token introspection, and OpenTelemetry support.

Tokens
73.7K
Snippets
219
Records
347
Agent score
71%

What's inside Keycloak.AuthServices

  1. Overview of Keycloak.AuthServices packages

    main

    Keycloak.AuthServices is a family of NuGet packages designed to integrate .NET applications with Keycloak. The library covers authentication (OIDC/OAuth2/SAML), authorization (RBAC and Keycloak Authorization Server), and programmatic management via the Keycloak Admin and Protection REST APIs.

    Available packages include:

    • Keycloak.AuthServices.Authentication: Provides ASP.NET Core integration for JwtBearer and OpenIdConnect protocols.
    • Keycloak.AuthServices.Authorization: Provides Role-Based Access Control (RBAC) and integration with the Keycloak Authorization Server.
    • Keycloak.AuthServices.Sdk: Provides integration with the Keycloak Admin REST API (for managing users, groups, and realms) and the Protection REST API (UMA-compliant endpoints).
    • Keycloak.AuthServices.Sdk.Kiota: Provides integration with the Keycloak Admin REST API using a client generated from the OpenAPI Specification.
  2. Overview of Keycloak.AuthServices Packages

    main

    The library is modular. Select the package that matches your architectural needs:

    PackagePurpose
    Keycloak.AuthServices.AuthenticationJWT Bearer (Web API) and OpenID Connect (Web App) authentication
    Keycloak.AuthServices.AuthorizationRBAC (realm/client roles), Authorization Server client, [ProtectedResource] attribute, organization authorization
    Keycloak.AuthServices.SdkHand-written Admin REST API + Protection API HTTP clients
    Keycloak.AuthServices.Sdk.KiotaAuto-generated (Kiota) Admin REST API client — full API coverage
    Keycloak.AuthServices.CommonShared configuration (KeycloakInstallationOptions), claims utilities
    Keycloak.AuthServices.OpenTelemetryMetrics and tracing instrumentation
    Keycloak.AuthServices.Aspire.Hosting.NET Aspire KeycloakResource integration
    Keycloak.AuthServices.Templatesdotnet new project templates
  3. Choose a Keycloak Admin REST API SDK

    main

    Keycloak.AuthServices provides two different NuGet packages for interacting with the Keycloak Admin REST API, depending on your requirements for coverage and implementation style:

    • Keycloak.AuthServices.Sdk: A manually written, typed HTTP Client. It is high quality but does not implement the full functionality of the Admin API.
    • Keycloak.AuthServices.Sdk.Kiota: A client generated from the OpenAPI Specification. It provides full functionality coverage of the API.

    Note that the Admin API is protected; you must implement access token management to avoid 401 (Unauthorized) errors.

  4. UMA Resource Sharing Sample Architectures

    main

    The UMA samples are provided in two distinct architectural patterns depending on your application structure:

    Blazor + Resource Server

    Architecture: Blazor Server $\rightarrow$ WebAPI $\rightarrow$ Keycloak This is a two-project setup. It uses UmaTokenHandler (a DelegatingHandler) to transparently handle 401 UMA challenges that occur between the Blazor client and a separate Resource Server API.

    Razor Pages (Self-Contained)

    Architecture: Razor Pages $\rightarrow$ Keycloak This is a single-project setup where the application itself acts as the resource server. It uses IAuthorizationService to check permissions inline and IKeycloakProtectionClient to manage permission tickets. There is no separate API in this model.

  5. Choose between Hand-Written and Kiota-Generated Admin SDKs

    main

    The library provides two distinct SDK options for interacting with the Keycloak Admin REST API depending on your needs for API coverage versus code quality:

    1. Keycloak.AuthServices.Sdk (Hand-written): Provides high-quality, typed clients but only offers partial coverage of the Keycloak Admin API.
    2. Keycloak.AuthServices.Sdk.Kiota (Kiota-generated): Provides full API coverage by generating a fluent client from the OpenAPI specification, though it may differ in style from hand-written code.
  6. Resource Authorization Use Cases

    main

    The Resource Authorization sample demonstrates several authorization patterns using Keycloak's authorization services:

    • Role-based access to protected resources: Restricting access to a protected resource (e.g., "workspaces") based on RealRoles extracted from claims.
    • Resource-type policies: Implementing policies that apply to all resources of a specific type (e.g., allowing an "Admin" to manage all workspace-type resources).
    • Resource-specific policies: Implementing policies for a particular, unique resource instance (e.g., allowing a user to list specific workspace names).
    • Relationship-based access: Restricting access to details or members of a workspace to only those who are members of that specific workspace.
    • Anonymous access precedence: Demonstrating that AllowAnonymous settings on a ProtectedResource take precedence over other authorization requirements, allowing unauthorized users to access public resources.
  7. What is the Protection API

    main

    The Protection API is a UMA-compliant (User-Managed Access) set of endpoints used for managing authorization in Keycloak. It provides three main capabilities:

    • Resource Management: Allows resource servers to manage resources remotely and enables policy enforcers to query for resources requiring protection.
    • Permission Management: Enables resource servers to create permission tickets and manage the state of permissions.
    • Policy API: Allows resource servers to manage permissions for users by setting permissions on resources on behalf of those users.
  8. What is UMA 2.0 (User-Managed Access)?

    main

    User-Managed Access (UMA) is an OAuth-based protocol that allows a resource owner to control access to their protected resources. Unlike standard OAuth where the resource server makes access decisions, UMA supports an asynchronous approval model: a requesting party can request access to a resource, and the resource owner can review and approve or deny that request later.

    Key Concepts

    ConceptDescription
    Resource OwnerThe user who owns the protected resource (e.g., alice)
    Requesting PartyA user who wants to access someone else's resource (e.g., bob)
    Resource ServerThe API that hosts and protects resources
    Authorization ServerKeycloak — evaluates policies and issues permission tickets and RPTs
    Permission TicketA one-time challenge token representing an access request
    RPT (Requesting Party Token)An access token enriched with specific resource permissions
    Permission RequestA pending approval request created via the Protection API Permission Ticket endpoint
  9. What is User-Managed Access (UMA)?

    main

    User-Managed Access (UMA) is an OAuth-based protocol that allows a Resource Owner to control access to protected resources asynchronously. Unlike standard OAuth, UMA enables a Requesting Party to request access to a resource, which the owner can then review and approve or deny at a later time without being online during the initial request.

    Key UMA Concepts

    ConceptDescription
    Resource OwnerThe user who owns the protected resource (e.g., alice)
    Requesting PartyA user who wants to access someone else's resource (e.g., bob)
    Resource ServerThe API that hosts and protects resources
    Authorization ServerKeycloak — evaluates policies and issues permission tickets and RPTs
    Permission TicketA one-time challenge token representing an access request
    RPT (Requesting Party Token)An access token enriched with specific resource permissions
    Permission RequestA pending approval request created via the Protection API Permission Ticket endpoint
  10. Understand Keycloak Caching

    main

    Keycloak uses several cache types to optimize performance. In clustered mode, these caches use distributed invalidation to maintain consistency across nodes. You can configure max entries, lifespan, and eviction policy (e.g., LRU).

    CacheContent
    RealmRealm configuration
    UserUser data from federation sources
    KeysSigning and encryption keys
    AuthorizationPermissions and policies
  11. How Token Introspection works

    main

    The introspection process follows these steps as an IClaimsTransformation:

    1. Skip check: If realm_access or resource_access claims are already present in the JWT, the token is not considered lightweight and introspection is skipped.
    2. Token extraction: The bearer token is extracted from the Authorization header.
    3. Cache lookup: Checks HybridCache for a cached response using the jti claim or a SHA256 hash of the token.
    4. Introspection call: On a cache miss, a POST request is sent to /realms/{realm}/protocol/openid-connect/token/introspect containing the token, client_id, and client_secret.
    5. Claim enrichment: Introspected claims are added to the ClaimsIdentity.
    6. Role mapping: KeycloakRolesClaimsTransformation maps roles from the newly enriched claims.