Update Refresh Token within Interceptor prior to sending request

I'm stuck on this problem and could use some guidance. My goal is to refresh a user's access token when it is close to expiration.

The authService.isUserLoggedIn() function returns a promise that checks if the user is logged in. If not, the user's access token needs to be refreshed.

The issue I'm facing is that authService.isUserLoggedIn() is an asynchronous call, so the interceptor finishes its execution before the promise is resolved, leading to the Authorization header not being updated with the new token.

I have been trying to find a way to wait for the promise to resolve before continuing with the script, but so far, I haven't been successful in achieving the desired outcome.

Below is the current code snippet:

.factory('SEHttpInterceptor', function($injector, ngWebApiSettings) {
    return {
        // optional method
        'request': function(config) {

          // add Authorization header if available
          if (config.url.indexOf(ngWebApiSettings.apiServiceBaseUri) >-1){
            var authService = $injector.get('authService2');
              authService.isUserLoggedIn().then(function(response){
                var authData = $injector.get('$localStorage').getObject("authorizationData");
                config.headers.Authorization = 'Bearer ' + authData.token;
              });
          }   
          return config;
        }
      };
});

Answer №1

According to the documentation on AngularJS $http:

The interceptors utilize promise APIs for both synchronous and asynchronous pre-processing.

request: Interceptors receive a http config object. The function can modify or create a new config object. It should return the config object directly, a promise with the config, or a new config object.

It seems like you could do the following:

'request': function(config) {

    if (config.url.indexOf(ngWebApiSettings.apiServiceBaseUri) === -1){
        return config;
    }

    var authService = $injector.get('authService2');
    return authService.isUserLoggedIn().then(function(response){
        var authData = $injector.get('$localStorage').getObject("authorizationData");
        config.headers.Authorization = 'Bearer ' + authData.token;
        return config;
    });

}

Answer №2

Special thanks to Oleg for suggesting a solution that finally got this functionality up and running successfully. The key was implementing a promise that included returning the config key.

.factory('SEHttpInterceptor', function($injector, ngWebApiSettings) {
     return {
        // optional method
        'request': function(config) {

          // checking and adding Authorization header as needed
          if (config.url.indexOf('/Token')== -1 && config.url.indexOf(ngWebApiSettings.apiServiceBaseUri) >-1){
            var authService = $injector.get('authService2');
              return authService.isUserLoggedIn().then(function(response){
                var authData = $injector.get('$localStorage').getObject("authorizationData");
                config.headers.Authorization = 'Bearer ' + authData.token;
                return config;
              });
          }   
          return config;
        }
      };
    })

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

Having trouble uploading several files with Multer functionality?

I've encountered an issue with Multer in Node.js where I can't seem to select and upload multiple files. In a previous exercise, I had no trouble uploading a single file, but now I'm struggling with enabling multiple uploads. What am I mis ...

Retrieve a collection of paths using $routeProvider in Angular

I am working on an app that defines routes in the following manner: angular.module('myApp').config(['$routeProvider', function ($routeProvider) { 'use strict'; $routeProvider .when('/user-management', { ...

Occurrences repeating several times following the incorporation of fresh content into the DOM

I am facing an issue with my plugin. I have implemented an update method to handle new elements added to the DOM. Initially, everything works perfectly without any errors or issues. However, when a new element (div with class "box") is added to the DOM, th ...

Unlock hidden content with a single click using jQuery's click event

I have a question that seems simple, but I can't quite get the syntax right. My issue is with a group of stacked images. When I click on an image, I want it to move to the front and display the correct description above it. Currently, clicking on the ...

The unusual behavior of the :to attribute on @click in Vue

I have a specific element: Hashtag.vue: <template> <router-link :to="getTo" custom v-slot="{ navigate }"> <div role="link" @click="navigate"> {{text}}</div> </rout ...

The Angular promise refuses to resolve at my desired time

I am struggling with managing Angular promises in order to control when they resolve. In the code snippet below, my intention is to first retrieve KeyDataFromServer() and then proceed with executing the remaining commands only after all the keys have been ...

What could be causing the error 404 message to appear when trying to retrieve video data?

I'm having trouble displaying a video in mp4 format from the code's folder. When I attempt to fetch the video by clicking on the button, it shows an empty space instead of displaying the video. Here is an example of what the output looks like. T ...

Issue with Angular application failing to fetch data from JSON server

I've been attempting to retrieve data from a local server, but so far I'm not getting any results. The concept is to have a service handle the retrieval process and return an observable for any components in need of the data to subscribe to. dis ...

Frontend utilizing the Next-auth Github Provider for Profile Consumption

After following the official documentation for implementing SSO with the Next-auth Github provider in my App, I encountered an issue where the Client API documentation suggested using useSession() to retrieve session information, but it was not returning t ...

Why won't NextJS Image elements render on iOS 16 when they are not in the viewport initially?

I opted to implement NextJS for enhanced routing capabilities and image optimization. However, I encountered an issue with certain images failing to load properly on iOS devices. The problem arises within a scrollable horizontal container featuring Product ...

Implementing a unique sorting algorithm for an array of numbers in Angular

I need to organize an array of numbers in descending order with a custom sorting method based on a specified number, all without splitting or filtering the array. I am currently working with Angular 17 and Rxjs 7.8. For instance, if I have this array of n ...

What is the best way to execute a JavaScript file with npm scripts?

Trying to use npm but encountering some issues. In my package.json file, I have: "scripts": { "build": "build.js" } There is a build.js file in the same folder that simply console.logs. However, when I execute npm run build I receive the error messag ...

Encountering an issue while fetching information from a JSON file using JavaScript

I am encountering an Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data let mydata = JSON.parse("file.json"); console.log(myJSON) Here is a sample of the JSON file's data: [[1,1,0,1,1,0,0,0,1,1,1,1,1, ...

Troubleshooting Issue: XMLHttpRequest Incompatibility with Internet Explorer

I'm having an issue with the script below. It works fine on Firefox and Chrome but doesn't seem to work on IE. I've tried various solutions, including lowering the security settings on my browser, but it still won't work. function se ...

Is there a way for me to identify the vertical gaps in my code using JavaScript?

Within this specific HTML document, there are multiple div elements that have an absolute positioning applied to them I am looking to develop a JavaScript code that can determine the row of each individual div. I define a row as any space on the vertical ...

Fade in elements from an array using jQuery

Hey there, I'm currently facing an issue with using Javascript to process data within a function. Since I'm new to Javascript, I'm hoping for a simple explanation. My aim is to display each item from an array sequentially, with a fading in ...

Tips on avoiding the repetition of jQuery functions in AJAX responses and ensuring the effectiveness of jQuery features

My HTML form initially contains only one <div>. I am using an AJAX function to append more <div> elements dynamically. However, the JavaScript functionality that works on the static content upon page load does not work for the dynamically added ...

Retrieve the output from PHP in JSON format and then utilize jQuery to parse it

I am currently working on a jQuery function $.post(file.php), where the data is being sent to "file.php" and returned in JSON format using json_encode(). Although I am able to successfully retrieve the result, I am unsure how to separate the individual i ...

Determine whether the elements within an array are present on the webpage. If they are, display an alert. If not, reload the page

Initially, I had a userscript designed to search for a specific string within a webpage. If the script failed to locate the string, it would refresh the page after 4 seconds: var item = 'apple'; if(document.body.innerHTML.toString().indexOf(item ...

Building Individual Elements in Angular 2

My task involves creating two distinct components in Angular 2, the Users component and the Clients component. These components are not nested and do not have any relationship. To call these components separately, I typically use main.ts as the main entry ...