DEV Community

Cover image for JWT Says ‘Admin’. Should Your API Believe It?
Hadil Ben Abdallah
Hadil Ben Abdallah

Posted on

JWT Says ‘Admin’. Should Your API Believe It?

Exposes multi-tenant workspace isolation gaps

A JWT authorization check can look simple: your API receives a JSON Web Token, reads the user's roles from the Keycloak access token and grants access when the appropriate administrative role is present in realm_access.roles or resource_access.<client-id>.roles. The implementation might take only a few lines of code, but those lines can decide who gets access to sensitive customer data, administrative operations, and internal resources.

The problem is that a JWT is a container for claims. Seeing an admin role in realm_access.roles or resource_access.<client-id>.roles does not, by itself, prove that the user should have administrative access to your API. Your application needs to establish that the token is authentic, intended for the API, still valid, and issued under rules your system trusts.

This distinction matters in SaaS applications, where a single API often serves multiple organizations, user roles, and permission levels. A token that grants administrative access in one workspace must not accidentally provide the same access across every customer account.

Getting JWT authorization right means understanding what a token proves, which claims your API should trust, and where authorization decisions belong. Let's look at how to make those decisions without turning every API request into a security guessing game.


TL;DR

Your API should not grant administrative access just because a JWT contains an admin role in realm_access.roles or resource_access.<client-id>.roles. It should grant administrative access only after validating the token's signature, issuer, audience, and expiration, then checking that the authenticated user has the required permissions for the requested resource.

A secure JWT authorization implementation should:

  • Validate the token: Check its signature and verify that it comes from a trusted issuer.
  • Check its intended audience: Make sure the token was issued for your API.
  • Enforce expiration: Reject tokens that are expired or otherwise invalid.
  • Trust role claims only from trusted sources: An admin value must come from an authenticated and authorized identity system.
  • Check resource-level permissions: Confirm that the user can perform the requested action within the correct organization or workspace.
  • Keep authorization on the server: Never rely on frontend role checks or hidden interface elements to protect sensitive operations.

A JWT helps your API establish who made a request and what trusted claims accompany that identity. Your application still needs to decide what that user is allowed to do.


What Does an Admin Claim Tell Your API?

A JSON Web Token carries information about an authenticated identity. This information is stored as claims: statements about the subject, the token issuer, its intended audience, and other attributes associated with the authentication process.

When using Keycloak, role claims follow a specific structure. For example, an identity provider might issue an access token containing claims like these:

{
  "sub": "user-123",
  "iss": "https://identity.example.com/realms/saas",
  "aud": "saas-api",
  "exp": 1893456000,
  "realm_access": {
    "roles": ["admin"]
  },
  "resource_access": {
    "saas-api": {
      "roles": ["manage-members"]
    }
  },
  "organization": {
    "org-456": {
      "id": "org-456",
      "name": "Acme"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Here, sub identifies the user, iss identifies the issuer, and aud indicates the intended recipient. The exp claim defines when the token expires.

Keycloak stores realm-level roles in realm_access.roles and client-level roles in resource_access.<client-id>.roles. When the Organization client scope is enabled, the token can also include an organization claim identifying the organizations associated with the user.

When your API receives this token, it can use the claims to make authorization decisions after validating the token and establishing that the claims come from a trusted source.

However, the meaning of an administrative role depends on the authorization model behind it. Does it mean a platform administrator who can manage every customer account? An organization administrator who can manage one workspace? Or an administrator of a specific application module?

Those permissions are not interchangeable. A user who manages members inside one organization should not automatically gain access to billing settings or administrative functions across the entire SaaS platform.

A JWT contains claims, not automatic permissions

A common source of confusion is treating authentication and authorization as the same operation.

Authentication establishes the identity associated with a request. Authorization determines whether that identity has permission to perform a specific action on a specific resource.

A valid JWT helps with the first operation. Its trusted claims can contribute to the second, but they do not replace the application's permission checks.

For example, imagine a user sends a request to:

DELETE /api/organizations/org-456/members/user-789
Enter fullscreen mode Exit fullscreen mode

The token might contain an administrative role, but your API still needs to establish whether that role grants permission to remove members from org-456. It also needs to ensure that the requested organization matches the user's authorized scope.

This is where JWT authorization becomes more than checking a string. Your API needs to understand the context behind each permission before allowing a sensitive operation.

JWT authorization diagram showing the JSON Web Token header, payload, signature, and admin role claims


A Valid JWT Does Not Automatically Grant Admin Access

A JWT can have a valid signature, come from your trusted identity provider, and still fail to justify an administrative action. Token validation establishes that the token is authentic and meets the expected conditions. It does not establish that every permission written inside it applies to every resource in your application.

Consider a SaaS platform with several customer organizations. A user might be an administrator in Acme's workspace but have no administrative privileges in Globex's workspace. If your API checks for an admin role in realm_access.roles or resource_access.<client-id>.roles without verifying the token's issuer, audience, and organization context, it may grant access to the wrong user or tenant.

This is a tenant isolation problem, and it can expose customer data or give users control over resources they do not own.

The same role can have different scopes

The word admin is often too broad to describe what someone can actually do. A useful authorization model defines both the permission and the scope where that permission applies.

For example, your application might distinguish between these roles:

  • Platform admin: Manages platform-wide settings, infrastructure, and customer organizations.
  • Organization admin: Manages users, settings, and resources within one organization.
  • Project admin: Manages a specific project without gaining control over the entire organization.
  • Member: Uses the features and resources assigned to their account.

These roles represent different levels of authority. Your API must enforce those boundaries on every protected operation.

A role claim can help identify the user's permissions, but the API must also establish which organization, project, or resource those permissions cover. A request to modify an organization should never be authorized solely because the token contains a generic administrative role.

Token validity and permission are separate checks

A secure API handles these questions independently:

  1. Is this token valid? Verify its signature, issuer, audience, expiration, and other required claims.
  2. Who does it represent? Identify the authenticated subject.
  3. What is the requested action? Determine whether the user wants to read, create, update, or delete a resource.
  4. Does the user have permission in this context? Check the user's role and the scope of that role against the requested resource.

This separation makes JWT authorization easier to reason about and test. It also prevents a common mistake: treating successful authentication as permission to access every endpoint.


What Your API Must Validate Before Trusting a JWT

Before using a JWT's claims in an authorization decision, your API needs to validate the token itself. Reading the payload is easy, but decoding a JWT does not prove that its contents are genuine.

A JWT payload is typically Base64URL-encoded. Anyone who has the token can decode its readable claims without knowing the signing key. The signature provides the cryptographic protection that allows your API to detect unauthorized changes.

Here are the checks that belong in a secure JWT validation process.

1. Verify the signature

Your API must verify the token's cryptographic signature using the trusted issuer's public key or the appropriate shared secret, depending on the signing algorithm.

For tokens signed with an asymmetric algorithm such as RS256, the identity provider signs the token with its private key, and your API verifies it with the corresponding public key. This allows your API to validate tokens without holding the issuer's private signing key.

Never accept a token simply because its header declares an expected algorithm or because its payload contains familiar claims. Your validation library must enforce an explicit algorithm allowlist and reject unsupported or unexpected algorithms.

2. Check the issuer and audience

The iss claim identifies the authority that issued the token. Your API should accept tokens only from the expected issuer.

The aud claim identifies the intended recipient. A token issued for a different application or service should not automatically be accepted by your API, even when the signature is valid.

For example, a token intended for a frontend application is not necessarily suitable for an internal API. Your backend should check that the audience contains the identifier configured for that API.

These checks help prevent tokens issued in one context from being reused in another.

3. Configure the audience in Keycloak

Keycloak access tokens commonly include account as their default audience. If your API expects saas-api, checking for that audience can cause valid Keycloak tokens to fail validation.

To include your API in the token's audience, configure an Audience mapper in Keycloak:

  1. Open Client scopes in the Keycloak Admin Console.
  2. Create or select a dedicated client scope for your API.
  3. Open the Mappers tab.
  4. Select Add mapper → By configuration → Audience.
  5. Set the included audience to saas-api.
  6. Save the mapper and assign the client scope to the relevant client.

Configure the audience in Keycloak using Skycloak

After configuring the mapper, inspect a newly issued access token and confirm that its aud claim includes saas-api. Your API can then validate the expected audience.

4. Enforce expiration and time-based claims

JWTs commonly include exp, which defines the expiration time. Your API must reject expired tokens.

Other time-related claims can also matter:

  • nbf (Not Before): Defines the time before which the token must not be accepted.
  • iat (Issued At): Records when the token was issued and can support additional token-age policies.

Your validation logic should handle these claims according to the token profile and your application's security requirements. A small clock-skew allowance may be necessary when systems have slightly different clocks, but it should not become a way to accept expired tokens indefinitely.

5. Validate the token type and intended use

Not every JWT issued by an identity provider serves the same purpose. An ID token communicates authentication information to a client application, while an access token is intended to authorize access to a protected resource.

In Keycloak, the typ claim in the access token payload is Bearer, while an ID token uses ID. Your API should check that it receives an access token and reject ID tokens used as API credentials.

The API should also follow the issuer's token profile and validate any required claims, such as scopes or client identifiers, when those claims are part of its authorization model.

6. Use a trusted key source

When an identity provider publishes its signing keys through a JWKS endpoint, your API can retrieve the public keys and use them to verify incoming tokens.

The token header's kid value identifies the key used to sign the token. Your validation library uses it to select the matching public key from the trusted key set.

Signing keys rotate, so your API needs a reliable way to refresh its cached keys when the issuer publishes new ones. A well-maintained OIDC or JWT library handles much of this process and reduces the risk of implementing cryptographic verification incorrectly.

The important rule is simple: your API must validate tokens against keys obtained from a trusted issuer. It must never treat a key URL supplied by an untrusted token as a source of authority.

Example: Verify a Keycloak access token with jose

The jose library provides JWT verification and remote JWKS support. You can use it to validate a Keycloak access token's signature, issuer, audience, and signing algorithm:

import { createRemoteJWKSet, jwtVerify } from "jose";

const ISSUER = "https://<host>/realms/<realm>";

const JWKS = createRemoteJWKSet(
  new URL(`${ISSUER}/protocol/openid-connect/certs`)
);

export async function verifyAccessToken(token: string) {
  const { payload } = await jwtVerify(token, JWKS, {
    issuer: ISSUER,
    audience: "saas-api",
    algorithms: ["RS256"],
  });

  if (payload.typ !== "Bearer") {
    throw new Error("Not an access token");
  }

  return payload;
}
Enter fullscreen mode Exit fullscreen mode

Replace <host> and <realm> with your Keycloak deployment details. The expected audience must match the value configured in your Keycloak Audience mapper.

Once these checks succeed, your API has a verified identity and a set of trusted claims. The next step is using those claims to enforce permissions for the actual operation.


How to Handle Admin Permissions Safely

Once your API has validated a JWT, it can use the trusted claims as part of its authorization process. The important part is connecting those claims to the actual permissions your application enforces.

For a SaaS product, this usually means combining roles, scopes, and resource ownership. A user might have permission to manage members in one organization, access reports in another project, or update settings across a specific workspace. Your API needs to evaluate the right permission for each operation.

Define permissions around actual actions

A role such as admin is useful as a starting point, but it rarely describes every operation a user can perform. Defining permissions around actions gives your backend more control.

For example, an organization administrator might have these permissions:

{
  "organization": {
    "org-456": {
      "id": "org-456",
      "name": "Acme"
    }
  },
  "permissions": [
    "members:read",
    "members:invite",
    "members:remove",
    "settings:update"
  ]
}
Enter fullscreen mode Exit fullscreen mode

Your API can check the required permission for each endpoint. A request to invite a member requires members:invite, while changing organization settings requires settings:update.

This approach also makes it easier to introduce custom roles. A billing administrator might manage invoices and payment methods without gaining access to member management or security settings.

Enforce organization boundaries on every request

Role checks alone do not protect a multi-tenant application. Keycloak 26 introduces Organizations, which lets you associate users with organizations and include organization information in access tokens through the organization client scope. Your API must use this information to confirm that the user has access to the organization or resource identified in the request.

For example, a Keycloak access token can contain an organization claim like this:

{
  "sub": "user-123",
  "realm_access": {
    "roles": ["admin"]
  },
  "organization": {
    "org-456": {
      "id": "org-456",
      "name": "Acme"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

The user sends a request to:

GET /api/organizations/org-789/settings
Enter fullscreen mode Exit fullscreen mode

The API must recognize that the requested organization (org-789) is not among the organizations associated with the user in the token. The request should be rejected, even though the user has an admin role.

For users who belong to multiple organizations, Keycloak can include their organization memberships in the token. The backend should check the requested organization against the token's organization claim and verify the user's permissions for that organization. It should never accept an organization identifier from the frontend as proof of membership.

Keep authorization decisions on the server

Frontend role checks are useful for controlling the interface. For example, you can hide an administrative menu from users who cannot manage an organization. However, these checks do not protect the underlying API.

A user can modify browser requests, call endpoints directly, or change client-side state. Every sensitive backend operation must enforce its own authorization rules.

A practical implementation separates the authentication and authorization responsibilities:

  • Authentication middleware: Validates the access token and establishes the user's identity.
  • Authorization layer: Checks roles, permissions, and resource scope.
  • Business logic: Executes the operation only after the authorization check succeeds.

This structure gives your application one consistent place to enforce access rules. It also makes permission changes easier to maintain as the product grows.

JWT authorization flow showing API token validation, admin permission checks, organization scope verification, and access decisions

Example: Check an admin permission before an API operation

Here is a simplified TypeScript example showing how an API might enforce an organization-level permission after authentication:

type UserContext = {
  id: string;
  organizationId: string;
  permissions: string[];
};

function canManageMembers(
  user: UserContext,
  requestedOrganizationId: string
) {
  return (
    user.organizationId === requestedOrganizationId &&
    user.permissions.includes("members:invite")
  );
}

export async function inviteMember(
  user: UserContext,
  organizationId: string
) {
  if (!canManageMembers(user, organizationId)) {
    throw new Error("Forbidden");
  }

  // Continue with the member invitation.
}
Enter fullscreen mode Exit fullscreen mode

The example assumes that UserContext was created from an authenticated identity and trusted authorization data. It does not validate the JWT itself. That validation must happen before this function receives the user context.

In a production application, the authorization layer should also handle users with multiple organization memberships, permission inheritance, resource ownership, and the application's error-handling conventions. The core principle remains the same: check the permission and its scope before executing the operation.


Common JWT Authorization Mistakes

Even when a team uses a trusted identity provider and a well-maintained JWT library, small implementation decisions can create serious access-control weaknesses. These are some of the mistakes worth addressing early.

Trusting decoded claims without verifying the signature

Decoding a JWT only reveals its contents. It does not establish that the issuer created the token or that nobody modified its claims.

Your API must perform cryptographic signature verification before using any claim in an authorization decision. A decoded admin role in realm_access.roles or resource_access.<client-id>.roles has no authority until the token's signature and claims have been verified.

Treating every admin role as a platform-wide role

An organization administrator and a platform administrator have different responsibilities. Applying the same unrestricted admin check to both can expose resources across customer accounts.

Define role scope clearly and enforce organization or resource membership alongside role checks.

Accepting tokens issued for another application

A valid token can still be intended for a different client or API. Skipping audience validation creates an opportunity for token substitution, where a token issued for one purpose gets accepted in another context.

Check the expected audience and token type as part of your API's validation process.

Putting all authorization logic in the frontend

Hiding an admin button does not stop someone from calling the corresponding endpoint manually. The backend must enforce permissions for every protected operation, regardless of what the interface displays.

Assuming role changes take effect immediately

JWTs are self-contained, so an API can validate them without contacting Keycloak for every request. However, claims inside an already-issued token remain unchanged until the token expires or another mechanism invalidates it.

Keycloak's default access token lifespan is five minutes. If an administrator removes a user's privileges, an existing access token can still contain the previous role until it expires.

For sensitive operations that require up-to-date authorization information, your application can use Keycloak's token introspection endpoint:

POST /realms/{realm}/protocol/openid-connect/token/introspect
Enter fullscreen mode Exit fullscreen mode

Introspection allows the application to check the token's current status with Keycloak. Short-lived access tokens and server-side permission checks also help limit exposure from outdated role claims.


How Skycloak Fits Into a Secure JWT Authorization Architecture

JWT authorization depends on more than the API code that checks incoming tokens. Your identity provider also plays an important role by authenticating users, issuing tokens, managing roles, and providing the signing keys your applications use to validate those tokens.

This is where Keycloak fits into a SaaS architecture. It provides a centralized identity and access management platform for handling authentication, managing users and roles, and issuing OIDC tokens to your applications.

With Skycloak, your team gets managed Keycloak infrastructure while retaining full access to Keycloak's administration features.

Use Keycloak to manage identity and token issuance

Keycloak supports OpenID Connect and issues tokens after users successfully authenticate. Your API can use the access token to establish the identity associated with a request and validate its claims against the Keycloak realm that issued it.

You can also configure roles and client scopes in Keycloak to include relevant authorization information in tokens. For example, a SaaS application can use organization-specific roles to identify which administrative functions a user may access.

However, the API remains responsible for enforcing application permissions. Keycloak provides identity and token management, while your backend evaluates whether a user can perform a specific operation on a particular resource.

Keep your Keycloak infrastructure managed

Operating Keycloak yourself involves maintaining its servers, database, updates, security patches, availability, and backups. Those responsibilities become part of your team's workload as authentication becomes a core dependency for every customer-facing application.

Skycloak handles the underlying Keycloak hosting while giving your developers full administrative access. You can manage realms, clients, users, roles, identity providers, and authentication flows through the Keycloak Admin Console.

A few details make the service useful for SaaS teams:

  • Unlimited users: All Skycloak plans support unlimited users, with pricing based on infrastructure.
  • Full Keycloak admin access: Your team retains access to Keycloak's administration features and configuration.
  • Deployment regions: Paid plans let you choose your deployment region, while the free trial runs in the US.
  • Realm exports: You can export your Keycloak realms.
  • Free trial: Skycloak offers a 21-day free trial without requiring a credit card.

Your Next.js application and API continue using the standard Keycloak OIDC integration. You configure the issuer URL and client credentials for your deployment, validate the access tokens, and enforce your own authorization rules in the backend.

If you're building a SaaS product that needs centralized identity management without taking on the operational work of hosting Keycloak, explore Skycloak's pricing and plans to compare the available options for managed Keycloak infrastructure.


Frequently Asked Questions

Should an API trust the admin role in a JWT?
An API should trust an admin role only after validating the JWT's signature, issuer, audience, expiration, and intended use. It must also check that the role in realm_access.roles or resource_access.<client-id>.roles grants permission for the requested action and resource. A valid token containing an admin role does not automatically authorize every administrative operation.

Can someone modify the role inside a JWT?
Anyone holding a JWT can decode its payload and construct a modified version of the token. However, changing a claim without access to the signing key invalidates the original signature. An API that correctly verifies the signature rejects the modified token. This protection depends on using trusted signing keys and proper cryptographic validation.

What is the difference between JWT authentication and authorization?
JWT authentication establishes the identity associated with a token after the API validates it. Authorization determines whether that identity can access a resource or perform an operation. Authentication answers who is making the request; authorization answers what that user is allowed to do.

Should roles and permissions be stored inside a JWT?
JWTs can contain roles, scopes, and permission claims that help APIs make authorization decisions. However, those claims represent the authorization information available when the token was issued. Applications with frequently changing permissions or strict access requirements should also check current authorization data on the server.

Does Keycloak handle JWT authorization for my API?
Keycloak handles identity management, authentication, role configuration, and token issuance. Your API validates the access tokens and enforces permissions for its resources and operations. Keycloak provides the identity foundation, while your application defines and applies its own authorization rules.


Final Thoughts

A JWT that says admin gives your API information to evaluate, not permission to skip its security checks. Your backend must validate the token, establish the user's identity, and confirm that the requested action falls within that user's permissions and resource scope.

For SaaS teams, this distinction becomes essential as customer organizations, projects, and administrative roles grow. A clear authorization model helps prevent cross-tenant access and keeps sensitive operations under server-side control.

Keycloak provides a centralized way to manage identities, roles, and token issuance. With Skycloak handling the hosting infrastructure, your team can focus on building secure application access rules without taking responsibility for operating the identity platform.


Thanks for reading! 🙏🏻
I hope you found this useful ✅
Please react and follow for more 😍
Made with 💙 by Hadil Ben Abdallah
LinkedIn GitHub Twitter

Top comments (2)

Collapse
 
userxnom profile image
Abdullah Naseer •

The tenant-isolation example is the part that lands hardest — a valid signature plus an admin role in realm_access.roles still doesn't prove the user is an admin of org-456. One gap I noticed: the jose example validates the signature, issuer and audience, but I didn't see a check on the typ claim. Section 5 says to reject ID tokens used as API credentials — does the snippet actually enforce typ == "Bearer", or is that left to the reader? And how would you handle a token where the organization claim is missing entirely, say a legacy user created before Organizations was enabled — deny by default, or fall back to a database lookup?

Collapse
 
hadil profile image
Hadil Ben Abdallah •

You're right about the typ check. The jose example validates the signature, issuer, audience, and allowed algorithm, but those checks alone don't enforce the access-token type. I included that check as a separate step in the article, and it should definitely be reflected in the code example too.

For the missing organization claim, I'd avoid automatically granting access or assuming the user belongs to the requested organization. A database lookup can be a reasonable fallback for legacy users, provided it verifies their actual membership and permissions on the server. If neither the token nor the database can establish that relationship, the safest approach is to deny access by default.