Home > Mobile >  How to store JWT from Post-Response and send it in HTML-forms?
How to store JWT from Post-Response and send it in HTML-forms?

Time:10-30

I want to send a jwt with the uploaddata when the user has logged in. However when I click on the loginButton, the function login() should be called to make the post request along the formdata and to retrieve the JWT, but an "Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource" os shown in the console at login-function "const json = await data.json();".

Then when using the upload form, the JWT needs to be send as the authorauation header with the uploaded images as body. I want to accomplish this with plain javascript.

<form id="loginform" onsubmit="return login()" method="post">
    <input type="text" id="username" name="username" placeholder="Username">
    <input type="password" id="password" name="password" placeholder="Password">
    <input id="loginButton" type="submit">
</form>
    
<form id="uploadform" onsubmit="return convert_to_pdf()" method="post" enctype="multipart/form-data">
    <input type="file" id="images" name="images" multiple data-max="5" accept="image/jpg, image/jpeg, image/png" >
    <input id="sendImagesButton" type="submit">
</form>

<script type="text/javascript">
    async function login(){
        let data = await fetch("http://localhost:8000/api/login", {
            method: "POST",
            body: new FormData(loginform)
        });
        const json = await data.json();
        alert("test jwt retrieved");
        localStorage.setItem("token", json.access_token);
    }
    
    function convert_to_pdf(){
        let res = await fetch("http://localhost:8000/api/convert_to_pdf", {
            method: "POST",
            headers: {
                'Content-Type': 'multipart/form-data',
                'Authorization': ' Bearer '   localStorage.getItem("token")
            },
            body: new FormData(uploadform)
        });
    }
</script>

CodePudding user response:

From what i can see(not that much) i can say that the process of the authentication with JWT should be:

  • Send a POST request with the data you want in the token payload
  • In the server create the token
  • Send back the token(should be a single string, check it)

Now that you have access to the token on the client-side you can save it in the local or session storage(localStorage or sessionStorage).

Another option would be send the token on every request through cookies. It really depends on you.

EDIT: once you get the token back from the login request and you save it in the storage you have it available from anywhere in the client code, however the only way of sending it to the server via the update form(except using an hidden input) would be, in the script:

document.querySelector('#uploadform').addEventListener('submit', e => {
 // here you can access and manage your form value and also of course access the token value
 // to send it to client you can use something like axios so you would do
 e.preventDefault(); // that prevent the form to send its request
 // now send you request manually with your data for e.g.
 axios.post('http://localhost:8000/api/convert_to_pdf', /* your data here */)
})

CodePudding user response:

Default browser action for form submit by POST is to render response content. If it is not desired behavior you'll have to perform request from JS manually e.g. by using onsubmit attribute.

I found tutorial about that on Mozilla developer site.

Also you'll have to store JWT somewhere, maybe local-storage, when read it back and add it to Authorization header in next request, also done through JS and not standard browser submit.

  • Related