I'm creating an AngularJS application that uses the JWT token for authentication. The token is being passed using the AngularJS interceptor as shown below.
'request': function(config)
{
if (store.get('jwt_token') != null)
{
config.headers['x-access-token'] = store.get('jwt_token');
}
else
{
config.headers['x-access-token'] = '';
}
return config;
}
Whenever I'm accessing any /restricted
pages, everything is working fine. The issue is when I'm going to the /restricted
page by directly typing the URL in the address bar (or refreshing the page), the AngularJS gets circumvented, and hence, the Interceptors don't intercept the request, and the token is not passed.
I've been searching for a while, I found some solutions like responding with a piece of code that loads the AngularJS then makes a redirect from there. However, I'm looking for a simpler/neater approach if possible as I might be missing something here.
I can detect if the request came from AngularJS or not by checking for the x-access-token
since I'm always passing it (empty value if user is not authenticated).
Solution
Alex's answer is pointing to the exact problem, thanks Alex.
I finally figured it out yesterday. The solution I went with was to make sure all the requests come from AngularJS, I have a list of the restricted pages, if any of them is requested, I'm calling a function to verify and validate the JWT token on server side, if it's valid, proceed, otherwise, go to login page. The key thing is to ensure that ALL requests should go to the index.html to make sure AngularJS is handling the routing.
This link helped me greatly to solve this issue.
http://arthur.gonigberg.com/2013/06/29/angularjs-role-based-auth/
$http.defaults.headers.common.x-access-token = store.get('jwt_token');
in your app.js.store
? If it is some cookie service, than all is fine, because cookies are sent with request headers. If it is some localStorage etc, then what suggets @RahatMahbub should be enough ..