Show Redirect to Login Pop Up When Keycloak Refresh Token expired

December 21, 2023 · 3 min readLucian Ciobanu
Tags:AngularKeycloakHttpInterceptor

Keycloak is often use as an authentication and user management tool and it comes with a fair amount of functionality right our of the box. For the project I am currently involved in, we use it as the main authentication tool. The first thing I had to wrap my head around was the fact that it has two types of tokens - an authentication token and a refresh token. In my scenario, and probably the most common scenario, the authentication token which ensures access when calling the endpoints, will expire prior to the refresh token which is as valid as the session is. After the authentication token has expired, if the refresh token is still valid, a new authentication token will be created and handed over to the front end. What this meant is that after the refresh token had expired, my app would show an HttpError from the failing endpoint call but didn't mention to the user what happen so I set out to create a pop up which would let the user know the session has expired and a "go to login" button which would redirect to the login page. However, the events I could get from my keycloak instance were the following:

keycloak-event.d.ts

export declare enum KeycloakEventType {
  OnAuthError = 0,
  OnAuthLogout = 1,
  OnAuthRefreshError = 2,
  OnAuthRefreshSuccess = 3,
  OnAuthSuccess = 4,
  OnReady = 5,
  OnTokenExpired = 6,
  OnActionUpdate = 7
}

So after analyzing, I realized OnTokenExpired is triggered when the authentication token expires but it doesn't make sense to trigger any pop up based on this event because the authentication token expires prior to the refresh token so the user doesn't need to relogin at this moment.

Seeing Keycloak doesn't bring something clear out of the box, I've attached an event to all endpoint successful responses via an HTTP Interceptor and am checking if the refresh validity token is still the same. If it has changed, then I am triggering a new setInterval with the refresh validity coming from the back end, as such:

httpResponse.interceptor.ts

@Injectable()
export class HttpResponseInterceptor implements HttpInterceptor() {
  constructor(private service: Service) {}
  
  intercept(
    request: HttpRequest<unknown>
    next: HttpHandler
  ): Observable<HttpEvent<unknown>> {
    return next.handle(request).pipe(
      tap(() => this.service.checkToken())
    );
  }
}

and in service.ts

...
checkToken() {
  const refreshTokenValidity =
        this.keycloakService.getKeycloakinstance().refreshTokenParsed.exp;
}

//From here on out, I am checking with a global variable
//if the validity is the same and if not, I update the timeout

const refreshTokenValiditySeconds = refreshTokenValidity * 1000 - Date.now();
clearTimeout(this.sessionExpiresId);
this.sessionExpiresId = setTimeout(()) => {
  this.showSessionExpiredModal();
}, refreshTokenValiditySeconds);

I really enjoyed diving deeper into Keycloak as it's an accesible tool to use and easy on the budget.

Hope this helped!

Cheers,
Lucian

Picture of author

Web Development & Software Delivery