Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple JWT Auth using Jquery

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

like image 238
Shadid Avatar asked Nov 26 '25 14:11

Shadid


1 Answers

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

like image 90
Oleg Abrazhaev Avatar answered Nov 28 '25 02:11

Oleg Abrazhaev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!