[keycloak-user] Access Token not refreshed // KEYCLOAK-2517

Kuestermann, Thomas Thomas.Kuestermann at sabre.com
Fri Mar 9 09:53:01 EST 2018


Keycloak experts,

We're currently developing a Spring Boot based application and we're using Keycloak for the identity management. Works great so far. We recently updated Keycloak and the respective spring boot adapter and spring security module to 3.4.1.Final. 

We've configured access tokens with a lifespan of 5 minutes, I think that's also the default. After the upgrade we noticed that every HTTP call is answered with a 401 - Unauthorized after the access token timed out (due to inactivity in the application). This wasn't the case before. Keycloak documentation states that

> By default the application adapter will only refresh the access token when it's expired. [1]

which doesn't seem to work anymore.

I debugged the application and came across KEYCLOAK-2517 [2] which introduced KeycloakSecurityContextRequestFilter. Looking at the code, it seems that access tokens are only refreshed when they're valid:

+            if (refreshableSecurityContext.isActive()) {
+                KeycloakDeployment deployment = resolveDeployment(request, response);
+
+                if (deployment.isAlwaysRefreshToken()) {
+                    if (refreshableSecurityContext.refreshExpiredToken(false)) {
+                        request.setAttribute(KeycloakSecurityContext.class.getName(), refreshableSecurityContext);
+                    } else {
+                        clearAuthenticationContext();
+                    }
+                }
+            } else {
+                clearAuthenticationContext();
+            }

Otherwise the authentication context is cleared and access to resources is denied. 

Is this intended behavior? For me, it looks like a bug. If not, what's the general guideline on how to handle access token timeouts?

Our current workaround is to overwrite keycloakSecurityContextRequestFilter() in our derived KeycloakWebSecurityConfigurerAdapter like this:

+    @Override
+    protected KeycloakSecurityContextRequestFilter keycloakSecurityContextRequestFilter() {
+        return new KeycloakSecurityContextRequestFilter() {
+            @Override
+            public void doFilter(ServletRequest request, ServletResponse response,
+                    FilterChain filterChain) throws IOException, ServletException {
+                filterChain.doFilter(request, response);
+            }
+        };
+    }

It also look like others are facing the same issue [3].

Any help or pointer is highly appreciated.

[1] http://www.keycloak.org/docs/3.4/securing_apps/index.html#_refresh_token_each_req
[2] https://issues.jboss.org/browse/KEYCLOAK-2517 PR: https://github.com/keycloak/keycloak/pull/4741 
[3] https://github.com/jhipster/generator-jhipster/issues/6929

-- Thomas




More information about the keycloak-user mailing list