I am trying to implement jwt authentication for my nodejs, express and angularjs app. So far I have generated the token, and stored it in my localStorage
. According to this tutorial, I have implemented the authInterceptor
in angular factory as follows:
app.factory('authInterceptor', function ($rootScope, $q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.localStorage.myToken) {
config.headers.Authorization = 'Bearer ' + $window.localStorage.myToken;
}
return config;
},
response: function (response) {
if (response.status === "401") {
$window.location.replace('/dash');
}
return response || $q.when(response);
}
};
});
I have pushed the interceptor in config file as follows:
$httpProvider.interceptors.push('authInterceptor');
So far I have sent the credentials to server, generated the token and stored it in localStorage
.
So as long as I have not deleted the token from localStorage, and the token has not expired, I think it is supposed to persist. If I make requests from within the loaded page using the background ajax call of angularjs, the authentication header is set as it is supposed to.
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiYSIsInR5cGUiOiJzYWxlcyIsImlhdCI6MTQyMjI2MDExMCwiZXhwIjoxNDIyMjc4MTEwfQ.Iv6W-Tc8Qm4FGclzmgbtjvWFz_tyDwEvrFmMmucONpY
However neither my request nor my response is intercepted when I navigate to a new route. For eg, I have my '/sales' route. But when I navigate to sales route from address bar, neither the request authentication header is set by the interceptor, thus returning authorization error 401 from server, which is not intercepted either; hence not redirecting to /dash
.
Here is link of the error, and the headers of GET request to unauthorized route '/sales':