Store JWT token and redirect

Asked

Viewed 1,137 times

1

I created a login screen and when I click login I get back a JWT token and its expiration. What I want to do is store this token and redirect it to another page. I know I have to do the authorization using header but I don’t know exactly how to do it. I’m using Jquery

<form action="https://www.teste.teste.com:3000/api/v1/sign-in " method="post" name="login" id="login">
    <div class="box">
  <div class="box-top">
  <p style="position:absolute; top:30px; left:160px; color:white; font-size: 150%;">Logar</p>

    </div>

 </div>

<input type="text" id="name" class="input_text" name="name" placeholder="Usuário" value="pontual">

<div class="container">

<input type="password" id="password" name="password" class="input_text" placeholder="Senha" value="#P0ntu@l">

<input type="hidden" class="input_text" name="type_login" id="type_login" value="service"/>

<div>

 </div>

</div>

<button type="submit" id="salvar" name="myButton" value="foo">Logar</button>

    </div>
 </form>

That’s the return I get:

{
id: 1,
name: "pontual",
token: "JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NTU1OTM4OTksImlkIjoxLCJuYW1lIjoicG9udHVhbCIsInR5cGVfbG9naW4iOiJzZXJ2aWNlIn0.WJuGoxa0ditgNhylkKkXBacvqUAA7GXDIeJCW5v1rOU",
token_expires: "2019-04-18 10:24:59"
}

2 answers

1

Hello Gabriel all right?

You can store the token in the client localStorage or in a cookie. But apparently you are trying to send the POST token of a Ubmit form in which we know that it is not possible to control the headers in a form so either we send a cookie or one in the parameters of our form with a hidden input that is what it is apparently trying to do.

<input type="hidden" name="LTI-Authorization" value="Token consumerKey:consumerSecret" />

You can use the Ajax request:

$.ajax({
    type: 'POST',
    url: url,
    headers: {
        "LTI-Authorization":"Token consumerKey:consumerSecret"
    },
    data: {
       "lti_version":"${lti_version}" // all other data
    }
}).done(function(data) { 
    alert(data); 
});

If you are interested in doing a different POST Ajax using XHR.

$.ajax({
    type: "POST", //GET, POST, PUT
    url: '/authenticatedService'  //a url para a chamada
    data: seusDados,     //Dados a serem enviados para o server
    contentType: contentType,           
    beforeSend: function (xhr) {   //Inclui o bearer token no header 
        xhr.setRequestHeader("Authorization", 'Bearer '+ jwt);
    }
}).done(function (response) {
    //Response ok. process reuslt
}).fail(function (err)  {
    //Error during request
});

Hope I helped, hugs!

Sources: When auto-submitting a form, how do I add a header? JWT token with AJAX, non-AJAX, Jquery

  • Thanks for the answer! If I understand correctly (I’m still a beginner) where is the url I put the http I use in the form? And date I put specifically what? the login and password used?

  • Exactly Gabriel, in the URL are the data to where the request goes, and on the date will be the other data, see how your api wants to receive this data and assemble as requested by it.

1

Gabriel, as you asked how you would do.. follows another example:

HTML:

<input id="tokenField" type="hidden" />
<input id="submitButton" type="button" />

Javascript:

$('#submitButton').on('click',function(){
    $.ajax({
          url: "http://localhost:3000/api/valores",
          type: 'POST',
          contentType: 'application/json',
          headers: {
                    "Authorization": "Bearer " + $('#tokenField').val()
                 },
          async: false
            }});

SOURCE: How Set Authorization headers at HTML Form or at A href

  • 1

    tokenField is referring to the token that is returned as I put in the question?

  • That’s it. qq happens, as I commented earlier as far as I know (which is also not very rsrs) we cannot manipulate the header of the requests through form Ubmit. So we need to create a hidden field and insert the token into it. So briefly, yes is where your token would have to be sent.

  • Got it! , without wanting to abuse your good will takes away a doubt please? I created by form there, so that I pass the url in ajax I have to remove the form?

  • No Gabriel, you just need to create a Javascript function with this Ajax and call the function in the action of your form. Ex: <form action="#" onsubmit="Return validateFormOnSubmit(this);"> Reference: https://stackoverflow.com/questions/10520899/form-action-with-javascript/34467977

  • If these answers are helping you, please vote as useful and if you can solve your problem check as Answer ;D https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-accepta reply

Browser other questions tagged

You are not signed in. Login or sign up in order to post.