Pulling my hair out on this one. I would like to refresh an access token if the user's access token is just about to expire.
authService.isUserLoggedIn()
returns a promise and checks if the the user is logged in or not. If not the user's access token is being refreshed.
However the problem is that authService.isUserLoggedIn()
is async call and before it returns the value, the interceptor will finish its job and the Authorization header will not be populated with the new token...
I was looking for a way to wait for the promise to resolve before the script continues. Unfortunately I'm not able to 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;
}
};
});
From AngularJS $http documentation:
The interceptors leverage the promise APIs to fulfill this need for both synchronous and asynchronous pre-processing.
request
: interceptors get called with a http config object. The function is free to modify the config object or create a new one. The function needs to return the config object directly, or a promise containing the config or a new config object.
I'm assuming that 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;
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With