Reputation: 4252
I am trying to do a simple JWT Authentication using only JQuery. I have already tested the backend with postman and everything seems to work in there.
Here's how my frontend code looks like
$("#send").click(function(){
var name = $('#name').val();
var password = $('#password').val();
var token = ''
$.ajax({
type: 'POST',
url: '/authenticate',
data: { name: name , password: password },
success: function(resultData){
var token = resultData.token;
// console.log(token);
$.ajax({
type: 'GET',
url: '/memberinfo',
headers: {"Authorization": token},
success: function(data){
$(location).attr('href', '/memberinfo')
}
});
}
});
});
so when I get redirected to the memberinfo page it shows me I am unauthorised. Not quite sure if I am doing the Ajax calls properly. Would be really helpful if some one could direct me the right way. Thanks
Upvotes: 3
Views: 20822
Reputation: 41
You need to add word "Bearer":
headers: {"Authorization": "Bearer " + token}, // note the space after Bearer
Upvotes: 2
Reputation: 2839
For simple use case just retrieve a token in the login request response and save it to the localStorage or sessionStorage. Then use the token from the localStorage inside every request header. Please, have a look at an example code here.
https://github.com/chaofz/jquery-jwt-auth
On the other hand that is not secure to store a token in these storages as it is not protected from XSS attacks.
You better store token in cookies and check your cookies policies to prevent CSRF attack.
Please read more here
Upvotes: 7
Reputation: 186
i may be wrong, but a quick look of your code it might be because you set the api call for GET request
and your client page the same url /memberinfo
. your test result using Postman
is working and also you are properly redirected to the /memberinfo
upon success validation, however, since you are redirected to the same /memberinfo
url and your browser didn't send headers: {"Authorization": token}
you received unauthorised
result.
try to make the api call url different with the client member page.
Upvotes: 2