Simple JWT Auth using Jquery

15,782

Solution 1

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

Solution 2

You need to add word "Bearer":

headers: {"Authorization": "Bearer " + token}, // note the space after Bearer

Solution 3

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.

Share:
15,782
Shadid
Author by

Shadid

Software craftsman with a passion for web applications, AI and automation. continuously learning and seeking new opportunities where I can apply my technical skills to solve interesting problems and transform complication into simplicity.

Updated on June 04, 2022

Comments

  • Shadid
    Shadid almost 2 years

    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

  • Alcides Bezerra
    Alcides Bezerra almost 5 years
    Storing jwt tokens on local storage is not recommended, your application will be vulnerable to XSS attacks. Take a look at this article: stormpath.com/blog/…