token setting in headers and verification in jsonwebtoken - angularjs

I am working on a web app in which i am trying to implement jwt authentication for security. I am sending the generated token to the client side and saving it in headers but when i am sending http request then header is showing empty on server side.
this is server side code part for login module.
var profile = {
name:rows[0].name,
email:rows[0].email,
role:rows[0].role_id
};
var token = jwt.sign(profile,'shhhhhhared-secret',{expiresInMinutes: 60*5 });
res.json({
success: true,
user: rows[0], //userobject
token: token
});
this is the controller part where we are setting the response in sesssionstorage.
dbServices.UserAuthenticate($scope.email,
$scope.password).then(function(response) {
$rootScope.showLoader = false;
if (response.data.success) {
var session_data = {
'token':response.data.token,
'user':{
'name':response.data.user.name,
'role':response.data.user.role_id,
'email':response.data.user.email
}
};
sessionStorage.sessionData = JSON.stringify(session_data);
$location.path('/');
} else {
$scope.msg = 'Invalid Email or Password!'
}
})
this is config file where i am setting headers
App.factory('authInterceptor', ['$rootScope', '$q', '$window',
function($rootScope, $q, $window) {
return {
request: function(req) {
req.headers = req.headers || {};
if (sessionStorage.sessionData.token) {
req.headers.Authorization = 'Bearer ' + sessionStorage.sessionData.token;
}
return req;
},
response: function(response) {
if (response.status == 401) {
console.log('header auth 401 login');
$window.location = '/login';
}
return response || $q.when(response);
}
}
}
]);
App.config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
});
I am not getting whats going wrong in this. Can anybody help me out.

You do JSON.stringify(session_data) when saving the token but you don't do JSON.parse(sessionStorage.sessionData) before reading it.
Try changing
if (sessionStorage.sessionData.token) {
req.headers.Authorization = 'Bearer ' + sessionStorage.sessionData.token;
}
with
var session_data = JSON.parse(sessionStorage.sessionData);
if (session_data.token) {
req.headers.Authorization = 'Bearer ' + session_data.token;
}

Related

AngularJS: Refresh expired JWT token on 401 response

I'm facing issue on refreshing expired JWT token based on 401 (unauthorized) header response. What i want is when user get 401 (header) response, than a new (refresh) JWT should generated by calling specific service (api).
I'm sending XSRF-TOKEN & access_token (JWT) in header response and these are working fine. I even also can get refresh (expired) token by calling api manually. But can't get it worked with 401 (header) response.
I've a factory that take care of this promise and intercepts header requests. My (factory) code looks like this.
angular.module('myApp').factory('httpRequestInterceptor', httpRequestInterceptor);
function httpRequestInterceptor($cookies, $rootScope, $q, $location, $injector) {
var replays = [];
var refreshTokenPromise;
var factory = {
request: request,
responseError: responseError
};
return factory;
//////////
function requestTodoWhenDone() {
var token = store.get('token');
return $http({
method: 'POST',
url: ApiEndpoint.url,
params: {
grant_type: 'refresh',
id_token: $cookies.get('access_token')
}
})
.success(function(response) {
// Set the refreshed token.
$cookies.put('access_token', response.data.access_token);
})
.then(function(){
// Attempt to retry the request if request config is passed.
if( !angular.isUndefined(requestTodoWhenDone) && requestTodoWhenDone.length > 0 ) {
// Set the new token for the authorization header.
requestTodoWhenDone.headers = {
'Authorization': 'Bearer ' + $cookies.get('access_token')
};
// Run the request again.
return $http(requestTodoWhenDone);
}
});
}
//////////
// Add authorization token to headers
function request(config) {
config.headers = config.headers || {};
if ($cookies.get('access_token')) {
config.headers.Authorization = 'Bearer ' + $cookies.get('access_token');
}
return config;
}
// Intercept 401s and redirect you to login
function responseError(response, requestTodoWhenDone) {
if (response.status === 401 && $cookies.get('access_token')) {
return checkAuthorization(response);
}
return $q.reject(response);
/////////
function checkAuthorization(res) {
return $q(function(resolve, reject) {
var replay = {
success: function(){
$injector.get('$http')(res.config).then(resolve, reject);
},
cancel: function(){
reject(res);
}
};
replays.push(replay);
console.log(replays);
if (!refreshTokenPromise) {
refreshTokenPromise = $injector.get('requestTodoWhenDone') // REFRESH TOKEN HERE
.refreshToken()
.then(clearRefreshTokenPromise)
.then(replayRequests)
.catch(cancelRequestsAndRedirect);
}
});
////////////
function clearRefreshTokenPromise(auth) {
refreshTokenPromise = null;
return auth;
}
function replayRequests(auth) {
replays.forEach(function(replay) {
replay.success();
});
replays.length = 0;
return auth;
}
function cancelRequestsAndRedirect() {
refreshTokenPromise = null;
replays.forEach(function(replay) {
replay.cancel();
});
replays.length = 0;
$cookies.remove('token');
var $state = $injector.get('$state');
// SET YOUR LOGIN PAGE
$location.path('/login');
}
}
}
}
Based on above code I'm getting following error in console when token expires (401 response).
Console Error
Error: "[$injector:unpr] Unknown provider: requestTodoWhenDoneProvider <- requestTodoWhenDone
Any help on this would be highly appreciable.
Thanks.
Ok i ended up with different way that solves the issue. But i still can't be able to redirect user to login page when my token inactive time is also expires (this happens after jwt expires).
Here is the code.
authInterceptor.service.js
angular.module('someApp').factory('AuthorizationTokenService', AuthorizationTokenService);
AuthorizationTokenService.$inject = ['$q', '$injector', '$cookies'];
function AuthorizationTokenService($q, $injector, $cookies) {
// Local storage for token
var tokenVM = {
accessToken: null
};
// Subscribed listeners which will get notified when new Access Token is available
var subscribers = [];
// Promise for getting new Access Token from backend
var deferedRefreshAccessToken = null;
var service = {
getLocalAccessToken: getLocalAccessToken,
refreshAccessToken: refreshAccessToken,
isAccessTokenExpired: isAccessTokenExpired,
subscribe: subscribe
};
return service;
////////////////////////////////////
// Get the new Access Token from backend
function refreshAccessToken() {
// If already waiting for the Promise, return it.
if( deferedRefreshAccessToken ) {
return deferedRefreshAccessToken.promise
} else {
deferedRefreshAccessToken = $q.defer();
// Get $http service with $injector to avoid circular dependency
var http = $injector.get('$http');
http({
method: 'POST',
url: 'api_url',
params: {
grant_type: 'refresh',
id_token: $cookies.get('access_token')
}
})
.then(function mySucces(response) {
var data = response.data;
if( data ){
// Save new Access Token
$cookies.put('access_token', data.access_token);
if( $cookies.get('access_token') ) {
// Resolve Promise
deferedRefreshAccessToken.resolve(data.access_token);
// Notify all subscribers
notifySubscribersNewAccessToken(data.access_token);
deferedRefreshAccessToken = null;
}
}
}, function myError(error) {
deferedRefreshAccessToken.reject(error);
deferedRefreshAccessToken = null;
});
return deferedRefreshAccessToken.promise;
}
}
function getLocalAccessToken() {
// get accesstoken from storage - $cookies
if ( $cookies.get('access_token') ) {
var access_token = $cookies.get('access_token')
return access_token;
}
}
function isAccessTokenExpired() {
// Check if expiresAt is older then current Date
}
function saveToken(accessToken) {
// get accesstoken from storage - $cookies
var access_token = $cookies.put('access_token');
console.log('access_token ' + access_token);
return access_token;
}
// This function will call all listeners (callbacks) and notify them that new access token is available
// This is used to notify the web socket that new access token is available
function notifySubscribersNewAccessToken(accessToken) {
angular.forEach(subscribers, function(subscriber) {
subscriber(accessToken);
});
}
// Subscribe to this service. Be notifyed when access token is renewed
function subscribe(callback) {
subscribers.push(callback);
}
}
Than in config (app.js) I've following code which intercepts appropriate header(s) and refresh (request) api on 401 response.
Here is the config code
config.$inject = ['$stateProvider', '$urlRouterProvider', '$httpProvider'];
function config($stateProvider, $urlRouterProvider, $httpProvider) {
// Push httpRequestInterceptor
// $httpProvider.interceptors.push('httpRequestInterceptor');
//Intercept all http requests
$httpProvider.interceptors.push(['$injector', '$q', "AuthorizationTokenService", "$cookies", function ($injector, $q, AuthorizationTokenService, $cookies) {
var cachedRequest = null;
return {
request: function (config) {
//If request if for API attach Authorization header with Access Token
if (config.url.indexOf("api") != -1) {
// var accessToken = AuthorizationTokenService.getLocalAccessToken();
console.log('cookie ' + $cookies.get('access_token'));
config.headers.Authorization = 'Bearer ' + $cookies.get('access_token');
}
return config;
},
responseError: function (response) {
switch (response.status) {
// Detect if reponse error is 401 (Unauthorized)
case 401:
// Cache this request
var deferred = $q.defer();
if(!cachedRequest) {
// Cache request for renewing Access Token and wait for Promise
cachedRequest = AuthorizationTokenService.refreshAccessToken();
}
// When Promise is resolved, new Access Token is returend
cachedRequest.then(function(accessToken) {
cachedRequest = null;
if (accessToken) {
// Resend this request when Access Token is renewed
$injector.get("$http")(response.config).then(function(resp) {
// Resolve this request (successfully this time)
deferred.resolve(resp);
},function(resp) {
deferred.reject();
console.log('success: refresh token has expired');
});
} else {
// If any error occurs reject the Promise
console.log('error: refresh token has expired');
deferred.reject();
}
}, function(response) {
// If any error occurs reject the Promise
cachedRequest = null;
deferred.reject();
return;
});
return deferred.promise;
}
// If any error occurs reject the Promise
return $q.reject(response);
}
};
}]);
}
The code is working fine on 401 (response) case which happens when JWT expires. But its not redirecting me to login page (In this case I've added console in promise request in config instead of redirection code)
Please help on this, thanks...

angular auth interceptor on selected request

I have written an auth interceptor that adds auth token to the request and handles auth errors if the user is not logged in.
var storeApp = angular.module('storeApp');
storeApp.factory('authInterceptor', function ($q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
}
return config;
},
response: function (response) {
return response || $q.when(response);
},
responseError: function (response) {
if (response.status === 401 || response.data.error === 'token_not_provided') {
console.log('auth error');
}
return $q.reject(response);
}
};
});
storeApp.config(function ($httpProvider) {
$httpProvider.defaults.withCredentials = true;
$httpProvider.interceptors.push('authInterceptor');
});
The issue is the auth interceptor is added to every request, regardless the request requires authentication or not. What is the best way to create an auth interceptor that only intercepts when the route requires authentication?
You need the filter out the requests you want in the authInterceptor factory methods
['/whatever/1', '/whatever/2', '/whatever/3'].forEach(function(value){
if (response.config.url.startsWith(value)) {
// do something
}
})
return response;

Authentication: forced to refresh page to be authorised

I'm using the code from this blog to make an authentication module for my angular app.
I have a test page that includes a login form, a submit button and a "profile" button that will query a restricted route.
<div class="container-fluid" ng-controller="AuthCtrl as auth">
<input type="text" ng-model="auth.user.username">
<input type="text" ng-model="auth.user.password">
<button ng-click="auth.login(auth.user)">LOGIN</button>
<button ng-click="auth.profile()">PROFILE</button>
</div>
The restricted route I'm querying after login is defined as:
const authenticate = expressJwt({
secret: SECRET
});
app.get('/me', authenticate, function(req, res) {
res.status(200).json(req.user);
});
The login works fine. I receive a token that I put in sessionStorage.
When I click on the profile button (request to /me) I get an unauthorized error.
If I refresh the page and click again on profile I do get the excpected behaviour. (/me returns user data with no error)
If I delete the token manually after that, I still have access to /me until I refresh the page.
This is my service:
function loginService($http) {
this.login = function(user) {
return $http.post('/auth', user).then(
function(response) {
return response.data;
},
function(response) {
return response;
});
};
this.profile = function() {
return $http.get('/me').then(
function(response) {
return response.data;
},
function(response) {
return response;
});
};
}
angular
.module('app')
.service('loginService', loginService);
And this is my controller with the httpProvider:
function AuthCtrl($window, $http, loginService) {
this.user = {username: "", password: ""};
this.login = function(user) {
loginService.login(user).then(function(data) {
$window.sessionStorage.token = data.token;
});
};
this.profile = function() {
loginService.profile().then(function(data) {
console.log(data);
});
};
}
function config($httpProvider, $windowProvider) {
var window = $windowProvider.$get();
if(window.sessionStorage.token) {
var token = window.sessionStorage.token;
$httpProvider.defaults.headers.common.Authorization = 'Bearer ' + token;
}
};
angular
.module('app')
.config(config)
.controller('AuthCtrl', AuthCtrl);
Could the problem come from storing the token in sessionStorage or from the http provider?
Eventually I will implement the secure cookie method but I'd like to get this one solved before proceding further.
I finally figured out it was coming for the $httpProvider code.
function config($httpProvider, $windowProvider) {
var window = $windowProvider.$get();
if(window.sessionStorage.token) {
var token = window.sessionStorage.token;
$httpProvider.defaults.headers.common.Authorization = 'Bearer ' + token;
}
};
The provider options wer set only once during app load.
Reloading the page would rerun the config code and enter the if(window.sessionStorage.token) condition as expected.
To make this config dynamic, I had to create an interceptor (factory) like so:
function config($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
};
function authInterceptor($rootScope, $q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
}
return config;
},
responseError: function (rejection) {
if (rejection.status === 401) {
console.log("not authorised");
}
return $q.reject(rejection);
}
};
};
angular
.module('app')
.config(config)
.controller('AuthCtrl', AuthCtrl)
.factory('authInterceptor', authInterceptor);

Send request with auth token in header in angularjs

I implemented jwt stateless in backend , so except login and signup all other method has to intercept in angularjs and sending auth token to server in request header .But token is not sending mean not seeing in reqest header in console(developer tools).
This is my interceptor.js :
/**
*
*/
/* Interceptor declaration */
rootApp.factory('authInterceptor', function ($rootScope, $q, $sessionStorage, $location,$window) {
return {
request: function (config) {
//config.headers['Content-Type'] = 'application/json';
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
//config.headers['x-auth-token'] ='Bearer ' + $window.sessionStorage.token;
}
return config;
},
response: function (response) {
if(response.status === 200){
if(response.data && response.data.success === false){
if($rootScope.authFailureReasons.indexOf(response.data.reason) !== -1){
$location.path('/login');
}
}
}
if (response.status === 401) {
$location.path('/');
}
return response || $q.when(response);
},
'responseError': function (rejection) {
return $q.reject(rejection);
}
};
});
rootApp.config(['$httpProvider', function ($httpProvider) {
// $httpProvider.interceptors.push('headerInterceptor');
$httpProvider.interceptors.push('authInterceptor');
}]);
And service.js file is:
rootApp.service('adminService', function ($rootScope, $http, $q,$window) {
return {
inviteUser: function (user) {
var deferred = $q.defer();
$http({
method: 'POST',
url:$rootScope.baseUrl+'api/v1/admin/user/add',
data:user
}).success(function (response, status, headers, config) {
deferred.resolve(response);
}).error(function () {
// Something went wrong.
deferred.reject({'success': false, 'msg': 'Oops! Something went wrong. Please try again later.'});
});
return deferred.promise;
}
};
});
In server side X-AUTH-TOKEN is allowed in headers too.Where i am going wrong
Please help.
hey I have recently made my first token authentication in my Ionic app .. yeah it is an easy step but implementation may take some time if you are not a language PRO..
you can try this.
https://devdactic.com/user-auth-angularjs-ionic/
this is one of the finest and tested tutorial on the web for token based AUTH..
Maybe that may help you to find the error !

How to set default header values in Angular Resource?

The following approach does not work:
angular.module('myApp.myModule').factory('MyResource', function($resource, $cookies) {
var token = $cookies.get('token');
var user = $cookies.get('username');
console.log ("Token: "+token+" User: "+user);
return $resource(
'http://my-rest-api/whatever/:id',
{
headers: {
'token': token,
'user': user
}
}
)});
Console shows the correct data, but they were not sent..
That's the part somewhere in the related Controller (excerpt):
var getEntryOne = MyResource.get({ id: 1 }, function() {
console.log("Result: "+getEntryOne);
});
I get the "Message: Token invalid", I see the request-http-headers in firebug, they were not setted.
You are setting headers for get request then it should be there in get option of $resource
$resource('http://my-rest-api/whatever/:id',{},{
get:{
method:"GET",
headers:{
'token': token,
'user': user
}
},
});
If you wanted to add this header information to each request, then you could have http inteceptor which will be add header information on each request.
app.service('MyResourceInterceptor', ['$cookies', function($cookies) {
var token = $cookies.get('token'),
user = $cookies.get('username'),
service = this;
service.request = function(config) {
config.headers['token'] = token;
config.headers['user'] = user;
return config;
};
}]);
app.config([ '$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('MyResourceInterceptor');
}]);

Resources