Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
65
rated 0 times [  66] [ 1]  / answers: 1 / hits: 18761  / 8 Years ago, sat, january 14, 2017, 12:00:00

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


More From » jquery

 Answers
37

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


[#59356] Thursday, January 12, 2017, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
taylert

Total Points: 627
Total Questions: 91
Total Answers: 108

Location: Mayotte
Member since Mon, Sep 12, 2022
2 Years ago
taylert questions
;