top of page

Keycloak series | #3: Secure your API with JWT.

  • cymansys
  • Mar 24
  • 4 min read

Securing APIs is a critical step in building modern web applications. When your frontend uses Keycloak for authentication via OpenID Connect (OIDC), it’s essential to protect your backend API by validating the JWT tokens it receives. This post explains how to secure your API with JWT tokens issued by Keycloak, focusing on a Blazor Server frontend that handles authentication and passes the token to the API for authorization and expiration checks.



Configure Keycloak for the next step


From what we built in the earlier parts, we need to add a few more things for authorization.


Here are the steps required for this to work. We will need to add an audience, a claim for roles and a scope. Here's what you need to do.


1 - Create Realm Roles

In Keycloak Admin → movie-library realm → Realm roles → Create role:

  • Create movie-user

  • Create movie-admin


2 - Assign Roles to Test Users ( this is for test purposes)

Users → select your user → Role mapping → Assign role → select movie-user.


3 — Create the movielibrary_api.all Client Scope

This is what the Web frontend requests to get an API-ready access token.


  1. Go to Client Scopes → Create client scope

  2. Set:

    1. Name: movielibrary_api.all

    2. Type: Optional

    3. Include in token scope: ON

  3. Click Save


Now add two mappers to this scope (go to the scope → Mappers tab → Add mapper → By configuration):


Field

Value

Type

Audience

Name

movie-library-api-audience

Included Custom Audience

movielibraryapi

Add to ID token

Off

Add to access token

4

On


Mapper B: Realm Roles (flat roles claim)


Field

Value

Type

User Realm Role

Name

realm-roles-flat

Token Claim Name

roles

Add to ID token

Off

Add to access token

On

Multivalued

On


4 — Add the Scope to the movielibraryweb Client

Clients → movielibraryweb → Client scopes tab → Add client scope → select movielibrary_api.all → Add (as Optional).



How JWT and Keycloak Work Together


Keycloak acts as an identity provider that issues JWT tokens after a user authenticates. In a typical Blazor Server app, the frontend uses OIDC to authenticate users with Keycloak. Once authenticated, the frontend receives an ID token and an access token in JWT format.


The access token contains claims about the user and their permissions. This token must be sent with API requests to prove the user's identity and authorization level. The API then validates the token’s signature, checks its expiration, and verifies the user’s roles or scopes before allowing access to protected resources.


Setting Up Blazor Server with OIDC Authentication


To start, configure your Blazor Server app to authenticate users with Keycloak using OIDC:


  • Register your Blazor app as a client in Keycloak.

  • Configure the OIDC middleware in your Blazor Server app with Keycloak’s endpoints.

  • Handle user login and token acquisition seamlessly.


Also, add the new scope added to keycloak for the frontend.


This setup ensures the frontend obtains a valid JWT access token after login.


Passing the JWT to the API


Once the frontend has the JWT access token, it must include it in the Authorization header of API requests:


This header allows the API to identify the user and their permissions.


For this handler to work it needs to be registered in the program.cs


// Register the authenticated HTTP message handler builder.Services.AddTransient<AuthenticatedHttpMessageHandler>();


Validating JWT in the API


Your API needs to validate the JWT token on every request. Here’s what to check:


  • Signature: Confirm the token is signed by Keycloak using the public key.

  • Expiration: Verify the token has not expired.

  • Audience and Issuer: Ensure the token was issued for your API.

  • Claims: Check user roles or scopes to authorize access.


Example: Validating JWT in ASP.NET Core API


In an ASP.NET Core API, you can configure JWT authentication middleware like this:



This setup automatically validates the token signature, issuer, audience, and expiration.



Handling Token Expiration and Refresh


JWT tokens have a limited lifespan for security reasons. When a token expires, the API must reject requests with a 401 Unauthorized status. The frontend should detect this and request a new token using a refresh token or prompt the user to log in again.


In Blazor Server, you can manage token refresh by:


  • Using the OIDC middleware’s built-in refresh token support.

  • Automatically renewing tokens before expiration.

  • Handling unauthorized API responses to trigger re-authentication.


Securing API Endpoints with Authorization Policies


Beyond authentication, your API should enforce authorization rules based on user roles or claims in the JWT. For example, you can restrict certain endpoints to users with an "admin" role:



Apply this policy to controllers or actions:


This ensures only authorized users can access sensitive API parts.



Summary


Securing your API with JWT tokens from Keycloak involves several key steps:


  • Authenticate users in your Blazor Server frontend using OIDC with Keycloak.

  • Pass the JWT access token in API requests.

  • Validate the token’s signature, expiration, issuer, and claims in the API.

  • Handle token expiration gracefully with refresh tokens or re-authentication.

  • Enforce authorization policies based on JWT claims to protect sensitive endpoints.


Comments


bottom of page