Reputation: 6110
I have a standard Nodejs + Express + Angular application. After I read several tutorial about JSON Web Token from here, here and several more, I tried to implement JWT authentication in my application using this following procedures:
localStorage
on client's browser. Then I write a small javascript code to add my access_token
to each <a href="#">
in my application
$(document).ready(function(){
$("a:not([href])").each(function(){
var href= this.href;
var token = localStorage.getItem('token');
if(href.indexOf('?') >= 0){
href = href + "&access_token=" + token;
} else {
href= href + "?access_token=" + token;
}
$(this).attr('href', href);
});
});
The problem with this implementation are: it makes my URL ugly and exposes the token to address bar. I'm aware about custom header like x-access-token
or else, I even use this to get my access_token
var token = (req.body && req.body.access_token) || (req.query && req.query.access_token) || req.headers['x-access-token'];
My question is: How to send custom header with <a>
? Or is it the "correct" way to implement it ? Or someone have better solution ?
Upvotes: 0
Views: 255
Reputation: 1632
You could send custom http header by using $http service in a ng-click handler or something. If it is laborious to add ng-click to every A tag, you could write your directive code in which you can bind click handler automatically to every A tag and use $http service in click handler.
Directive code is something like this.
.directive('a', function($http){
return {
restrict: 'E',
link: function(scope, element, attrs) {
element.bind('click', function(){
console.log("You can use $http service.", $http);
});
}
}
})
Upvotes: 0