Update token in Interceptor before running request

Pulling my hair on it. I want to update the access token if the user access token expires.

authService.isUserLoggedIn() returns a promise and checks if the user is logged in or not. If the user access token is not updated.

However, the problem is that authService.isUserLoggedIn() is an asynchronous call and before it returns the value, the interceptor will complete its task and the authorization header will not be filled with a new token ...

I was looking for a way to wait for the promise to resolve before the script continues. Unfortunately, I cannot complete what is required.

code:

 .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; } }; }); 
+6
source share
2 answers

From AngularJS $ http documentation :

Interceptors use both APIs to meet this need for both synchronous and asynchronous preprocessing.

request : interceptors are called with the http config object. The function can freely modify the configuration object or create a new one. The function should return a configuration object directly or a promise containing a configuration or a new configuration object.

I assume you can simply:

 '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; }); } 
+2
source

Thanks to Olegโ€™s proposal, I managed to get this job. The answer was to return a promise in which we return the config key.

 .factory('SEHttpInterceptor', function($injector, ngWebApiSettings) { return { // optional method 'request': function(config) { // add Authorization header if available 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; } }; }) 
0
source

Source: https://habr.com/ru/post/981159/


All Articles