Revitalize access token with Keycloak in Javascript

I am currently working with keycloak-js version 8.0.1 and have a function called getToken that checks if the token is expired. If it is expired, the function refreshes it; otherwise, it returns the current token. The issue I am facing is that even though the warning message for an expired token is displayed, the token itself is not being updated.

TokenService

@Injectable()
export class TokenService {

static auth: any = {};

constructor() { }

 static init(): Promise<any> {
    const keycloakAuth: Keycloak.KeycloakInstance = Keycloak({
        url: config.keycloak.url,
        realm: config.keycloak.realm,
        clientId: config.keycloak.clientId
    });
    return new Promise((resolve, reject) => {
        keycloakAuth.init({ onLoad: 'check-sso', flow: 'implicit', checkLoginIframe: false }).success(() => {
            TokenService.auth.authz = keycloakAuth;
            resolve();
        }).error(() => {
            reject();
        });
    });
 }

 getToken(): Promise<string> {
    return new Promise<string>((resolve, reject) => {
        if (TokenService.auth.authz.isTokenExpired()) {
             console.warn("Token expired !");
            TokenService.auth.authz.updateToken(1800).success(() => {
                console.log("Token updated");
                resolve(<string>TokenService.auth.authz.token);
            }).error(() => {
                reject('Failed to refresh token');
            });
        } else {
            resolve(<string>TokenService.auth.authz.token);
        }
    });
 }
}

Answer №1

It appears that the issue may lie in the function

TokenService.auth.authz.updateToken(1800)
. This function is designed to refresh the token if it is going to expire within 1800 seconds, but since your token has already expired, no action is taken. I recommend bypassing the isExpired() check and directly implementing a solution like this:

getToken(): Promise<string> {
    return new Promise<string>((resolve, reject) => {
        TokenService.auth.authz.updateToken(100).success(() => {
                console.log("Token updated");
                resolve(<string>TokenService.auth.authz.token);
            }).error(() => {
                reject('Failed to refresh token');
            });
        resolve(<string>TokenService.auth.authz.token);
    });
 }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered: npm ERR! The function cb.apply is not defined when conducting the command npm install @angular/cli@latest

I encountered an issue with the message "npm ERR! cb.apply is not a function" on Windows while running the following command: > npm install I also attempted to resolve it by using: > npm install @angular/cli@latest However, the error persis ...

Tips for inserting values into a string array using jQuery or Angular 7

I have a series of checkboxes with values obtained from a loop. Instead of pushing these values into an array, I need to join them together as "parent1", "parent2", "parent3" and display the result in the console. Below is the code snippet for reference: ...

The declaration file for module 'react/jsx-runtime' could not be located

While using material-ui in a react project with a typescript template, everything is functioning well. However, I have encountered an issue where multiple lines of code are showing red lines as the code renders. The error message being displayed is: Coul ...

Encountering the error message "The argument type 'AsyncThunkAction<*>' cannot be assigned to the parameter type 'Action<any>'" while trying to utilize a custom typed useAppDispatch hook

For a live example, you can check out this link. In the process of developing a React application with TypeScript and Redux Toolkit, I have meticulously followed the guidelines outlined in the documentation. As a result, I have successfully implemented ty ...

How do I determine in Angular (2+) when all child components have been initialized from the parent component?

Is there a lifecycle hook named "ngAfterAllChildrenInit" that can be used because ngAfterViewInit is called before the ngOninit of the children? I am currently trying to find a solution that avoids using setTimeOut or emitting events from all of the child ...

Objects That Are Interconnected in Typescript

I have been delving into TS and Angular. I initially attempted to update my parent component array with an EventEmitter call. However, I later realized that this was unnecessary because my parent array is linked to my component variables (or so I believe, ...

Inject Angular 2 component into designated space

I am working on a website that requires a settings dialog to be loaded in a designated area upon clicking a button. The settings dialog is a component that retrieves data from REST endpoints. I am hesitant to simply insert the component and hide it as I ...

Guide to implementing a universal animated background with Angular components

I'm having trouble figuring out why, but every time I attempt to use a specific code (for example: https://codepen.io/plavookac/pen/QMwObb), when applying it to my index.html file (the main one), it ends up displaying on top of my content and makes ev ...

Ionic 3: Struggling to Access Promise Value Outside Function

I've encountered an issue where I am unable to retrieve the value of a promise outside of my function. It keeps returning undefined. Here's what I have attempted so far: Home.ts class Home{ dd:any; constructor(public dbHelpr:DbHelperProvider ...

JavaScript has a feature called "functions" which allow the declaration of named blocks of

Currently, I am developing an Electron app in typescript. In my main.ts file, I have instantiated a custom CommunicationProvider class object. What I want is for this class to declare multiple methods (specified in an interface that it implements) but have ...

How can I prevent further input in an input field after making a selection from mat autocomplete in angular?

Hello everyone, I am looking to disable the input field after selecting a value from the drop-down. Additionally, I want to be able to reset the selected value using a reset button. If you need a reference, you can check out Stackblitz: https://stackblitz ...

Display an error popup if a server issue occurs

I'm considering implementing an Error modal to be displayed in case of a server error upon submitting a panel. I'm contemplating whether the appropriate approach would be within the catch statement? The basic code snippet I currently have is: u ...

Having trouble choosing the component-button using Protractor

I'm having trouble selecting the "Add New" button using any locator component. Check out the audience.po.ts file and the method "ClickAddNewBtn()": clickAddNewBtn() { console.log("Clicking on the Add New button."); return element(by.cs ...

The presence of a setupProxy file in a Create React App (CRA) project causes issues with the starting of react-scripts,

I have implemented the setupProxy file as outlined in the documentation: const proxy = require('http-proxy-middleware'); module.exports = function (app) { app.use( '/address', proxy({ target: 'http ...

Showing the Enum name rather than the value in an Angular HTML template for a bound Typescript Interface

After retrieving an array of objects with various properties from a .NET Controller, I am utilizing the following Typescript code: import { Component, Inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Co ...

Encountering an error with the iconv-lite package in TypeScript code

I recently added the "iconv-lite" package to my project, imported the module, and attempted to use the decode method. However, I encountered the following error: TypeError: Cannot read properties of undefined (reading 'decode') Interestingly, ...

The Typescript compiler is unable to ignore imported JavaScript files

Recently, I started working with TypeScript and Angular 2, but encountered a problem that has left me puzzled. Initially, everything was going smoothly with the angular2 quickstart project until I attempted to import a plain JavaScript file. import * as m ...

Circular Dependency Detected in Angular 7 Library: A Tight Web of Directive, Service, and Module Interconnections

After setting up a new Angular 7 project with a library that includes a directive, a service, and a module (where the directive gets the service injected and the service has an injectionToken exported in the module), I encountered these warnings during com ...

Using the TranslateService in Angular to externalize an array of strings

I am new to externalizing code. As I was working on developing a month picker in Angular, I initially had an array of months with hardcoded names in my typescript file: arr = ['Jan', 'Feb', 'Mar', 'Apr', 'May&a ...

Identify alterations in a variable and trigger an event

I have a button labeled 'Refresh Data' that triggers the refreshBatchData() function: refreshBatchData(){ this.homeService.refreshData().subscribe(data => { this.batchSpotData = data; }) } After receiving data in batchSpo ...