16

I have single page application that is built using Angularjs and integrated with Keycloak for authentication and authorization.

I am able to login into my application, get loggedin user roles etc. goes The moment refresh token call, it always returns in my else case, and user logout of the application. Though the token valid time is set very high.

I need to update the token, if user has opened the app. In case of failure or expire token i need to logout the user. if (refreshed) always returns false.

Below is the piece of code i am using.

var __env = {};

        Object.assign(__env, window.__env);

        var keycloakConfig = {
            "url" : __env.keycloakUrl,
            "realm" : __env.keycloakRealm,
            "clientId" : __env.keycloakClientId,
            "credentials" : {
            "secret" : __env.keycloakSecret
            }
        };
var keycloak = Keycloak(keycloakConfig);
        keycloak.init({
            onLoad : 'login-required'
        }).success(function(authenticated) {
                 if(authenticated){                  
                        keycloak.loadUserInfo().success(function(userInfo) {
                        bootstrapAngular(keycloak, userInfo, roles);
                    });
            }
        });

function bootstrapAngular(keycloak, userInfo, roles) {
        angular.module('myApp').run(
                function($rootScope, $http, $interval, $cookies) {
                    var updateTokenInterval = $interval(function() {
                        // refresh token if it's valid for less then 15 minutes
                    keycloak.updateToken(15).success(
                                function(refreshed) {
                                    if (refreshed) {
                                        $cookies.put('X-Authorization-Token',
                                                keycloak.token);
                                    }else{
                                        $rootScope.logoutApp();
                                    }
                                });
                    }, 600000);
                    updateTokenInterval;
                    $cookies.put('X-Authorization-Token', keycloak.token);

                    $rootScope.logoutApp = function() {
                        $cookies.remove('X-Authorization-Token');
                        $interval.cancel(updateTokenInterval);
                        keycloak.logout();
                    };
    }
}
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116

6 Answers6

15

I couldn't find explained it in the API docs but the timeout argument of keycloak.updateToken() function is expressed in seconds, not in minutes.

So if the Access Token Lifespan on server is at the default value of 5 minutes, you should use a value less than 300 seconds. I learned it doing some experiments.

//Update the token when will last less than 3 minutes
keycloak.updateToken(180)

Btw I suggest you to use a Lifespan longer than 5 minutes for the token.

In your code You never see the token refreshed because the refresh is never triggered in the 15 seconds window in which will work.

Atropo
  • 12,231
  • 6
  • 49
  • 62
  • 6
    If you ever need to force refresh the token (for example to update the permissions in it) you can use `updateToken(-1)`. Do not abuse this... – Dan Manastireanu Aug 10 '20 at 08:52
  • If we request `updateToken` multiple times. Keycloak maintains a queue of these calls and only processes first `updateToken` request. Whenever the response of first `updateToken` is received, It immediately returns it's response for all of the remaining `updateToken` requests in queue. – Chetan Goyal Mar 21 '23 at 05:46
9

(refreshed) returns false only if your token is not expired. So you're trying to refresh the token when it has not yet expired.

set " Access Token Lifespan " to 1 minute in the Keycloak realm you're using, then try the following code to check the status of refreshed again

keycloak.onTokenExpired = ()=>{
            console.log('expired '+new Date());
            keycloak.updateToken(50).success((refreshed)=>{
                if (refreshed){
                    console.log('refreshed '+new Date());
                }else {
                    console.log('not refreshed '+new Date());
                }
            }).error(() => {
                 console.error('Failed to refresh token '+new Date());
            });
            }
Charith Jayasanka
  • 4,033
  • 31
  • 42
  • 2
    `So you're trying to refresh the token when it has not yet expired` Yeah thats it! Thanky you – Tazo leladze Oct 21 '20 at 18:30
  • 1
    Can you explain what does updateToken min validity param (50 on this case) means? On my case I have WebSocket connection and when token is expired the connection is closed and I retry, retry, retry... So can I say the token ever refreshed correctly and connection was opened? – Tazo leladze Oct 22 '20 at 08:52
  • If the token expires within minValidity seconds (minValidity is optional, if not specified 5 is used) the token is refreshed. If the session status iframe is enabled, the session status is also checked. This is what the documentation says – Charith Jayasanka Dec 07 '20 at 13:17
  • tokenExpired has to added before keycloak init – PPr Feb 24 '23 at 05:08
4

I take a look on their sample code:

        /**
     * If the token expires within `minValidity` seconds, the token is refreshed.
     * If the session status iframe is enabled, the session status is also
     * checked.
     * @returns A promise to set functions that can be invoked if the token is
     *          still valid, or if the token is no longer valid.
     * @example
     * ```js
     * keycloak.updateToken(5).success(function(refreshed) {
     *   if (refreshed) {
     *     alert('Token was successfully refreshed');
     *   } else {
     *     alert('Token is still valid');
     *   }
     * }).error(function() {
     *   alert('Failed to refresh the token, or the session has expired');
     * });
     */

So I think your token is still valid, that's why the updateToken return false.

Einsamer
  • 1,069
  • 4
  • 17
  • 34
1
keycloak.onAuthSuccess = function() { alert('authenticated'); }

keycloak.onTokenExpired = function () {
            keycloak.updateToken(5)
            .then(function (refreshed) {
                if (refreshed) {
                    alert('Token refreshed');
                  // write any code you required here
                } else {
                    alert('Token is still valid now');
                }
            }).catch(function () {
                alert('Failed to refresh the token, or the session has expired');
            }); }
            keycloak.init({ onLoad: 'login-required' }).then(function (authenticated) {..... }
PPr
  • 81
  • 4
  • How to update keycloak token when token gets expired in client side JavaScript refer ----https://github.com/keycloak/keycloak-documentation/blob/main/securing_apps/topics/oidc/javascript-adapter.adoc The adapter supports setting callback listeners for certain events. Keep in mind that these (onTokenExpired, onAuthSuccess onAuthRefreshSuccess etc ..)have to be set before the call to the init function. – PPr Feb 24 '23 at 05:26
0

In standard flow I noticed that Token expiration is coming form Access Token Lifespan and Refresh Token expiration from SSO Session Idle. And it is recommended that Access Token Lifespan should be shorter then SSO time out. Should it be the other way around? Also Access Token Lifespan can be overwritten in Clients Settings tab under Advanced Settings.

Alex Gontcharov
  • 111
  • 2
  • 8
-1

Have you looked at our Angular sample app https://github.com/keycloak/keycloak/blob/master/examples/demo-template/angular-product-app/src/main/webapp/js/app.js ? It could give you some tips maybe.

Sébastien Blanc
  • 2,929
  • 1
  • 12
  • 11