简体   繁体   中英

Keycloak token not active with angularjs

I have spring boot backend app with Angular js app. The login process and initial backend communication are successful. After some idle time, the front end will show 403 forbidden with token not active on the backend console.

The code below contains refresh token, But it seems not working.

// use bearer token when calling backend
themesApp.config(['$httpProvider', function($httpProvider) {
  var isExpired = keycloak.isTokenExpired();
  var token = keycloak.token;

  if (isExpired) {
    keycloak.updateToken(5)
    .success(function() {
      $httpProvider.defaults.headers.common['Authorization'] = 'BEARER ' + token;
    })
    .error(function() {
      console.error('Failed to refresh token');
    });
  }

  $httpProvider.defaults.headers.common['Authorization'] = 'BEARER ' + token;
}]);

Error on the backend

2017-05-29 10:08:23.715 ERROR 5072 --- [nio-8080-exec-3] o.k.a.BearerTokenRequestAuthenticator    : Failed to verify token

org.keycloak.common.VerificationException: Token is not active

Something must be wrong on the Keycloak Server, Token not active means token being is expired or is used before it gets valid. Could it be that the time/date is wrong on your KC server ?

you can config the 'Session Idle Time' here:

在此输入图像描述

I had the same issue and handle it with an automatical logout. So the user has to login again.

In your code:

var token = keycloak.token;

you define the value of token once. After the update you have to set it again:

// use bearer token when calling backend
themesApp.config(['$httpProvider', function($httpProvider) {
  var isExpired = keycloak.isTokenExpired();
  var token = keycloak.token;

  if (isExpired) {
    keycloak.updateToken(5)
    .success(function() {

     // UPDATE THE TOKEN
     token = keycloak.token;

     $httpProvider.defaults.headers.common['Authorization'] = 'BEARER ' +     token;
    })
.error(function() {
  console.error('Failed to refresh token');
});
}

 $httpProvider.defaults.headers.common['Authorization'] = 'BEARER ' + token;
}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM