Cases When Keycloak Returns Forbidden and AccessToken is Null


We’ve encountered a scenario in our staging environment where Keycloak returns Forbidden and the access token is null.

The code that identified the scenario:

public class AtnaResponseFilter {

    public void logUnauthorisedAccessAttempt(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
        if (responseContext.getStatus() == Response.Status.FORBIDDEN.getStatusCode()) {
            KeycloakSession session = org.keycloak.common.util.Resteasy.getContextData(KeycloakSession.class);
            var accessToken = Tokens.getAccessToken(session);

            if (accessToken == null) {
                // cannot reproduce locally but this happened in staging
                // when is this possible?

This situation has left us puzzled as we’re struggling to identify the specific request or condition that triggered this response.

Could anyone provide insights regarding the circumstances under which Keycloak might return a Forbidden status while the access token is null?

Thank you for your help