What is the process for storing a JWT-TOKEN in localStorage using JavaScript within an HTML script?

Currently, I am in the process of developing a web application using the Rest MVC architecture for an online store specializing in coffee and tea products. The technologies being utilized include Spring-Boot, Hibernate, PostgreSQL, Gradle, Thymeleaf, HTML, and CSS. The backend development is complete, and now it's time to work on the frontend. Specifically, I am focusing on creating an authorization page at the moment.

The design of the authorization page has been finalized with HTML and CSS, and now my task is to implement the authentication logic. This involves writing a javascript script that will securely store the generated jwt token in the user's localStorage. However, I'm facing a challenge in passing this token through the header using pure javascript.

It's crucial that the implementation of the javascript code remains clean and free from any external frameworks such as angular or node. How can I accomplish this task effectively?

Just to reiterate, the backend functionality related to Rest-based authorization is functional, where users can input their credentials (login and password) to receive a valid jwt token.

https://i.sstatic.net/KhjNk.png

Here is the snippet of the Java method responsible for handling the authentication:

 public ResponseEntity<Map<String, String>> authorization(@RequestBody AuthenticationRequestDTO requestDto) {
        try {
            String login = requestDto.getLogin();
            authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(login, requestDto.getPassword()));

            User user = userRepository.getByLogin(login);

            if (user == null) {
                throw new AuthenticationServiceException("ddwd");
            }

            String token = jwtTokenProvider.createToken(login, user.getRole());

            Map<String, String> response = new HashMap<>();
            response.put("login", login);
            response.put("token", token);

            return ResponseEntity.ok(response);

        } catch (AuthenticationServiceException e) {
            log.error("Error: ", e);
            throw new AuthenticationServiceException("Invalid login");
        }
    }

Answer №1

If you want to securely store and retrieve a JWT token, consider using localstorage. Here's an example on how to set and read values from localstorage.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">

function saveJwtTokenToLocalStorage(token) {
  localStorage.setItem("jwt_token", token);
}

function retrieveJwtToken() {
 var jwtToken = localStorage.getItem("jwt_token");
console.log("JWT Token: "+jwtToken );
return jwtToken ;

}
    
function getDataUsingJwtTokenInHeader(){
var jwtToken = retrieveJwtToken();
$.ajax({
    url: 'https://api.url',
    type: 'get',
    headers: {
        Authorization: "Bearer "+jwtToken,
    },
    dataType: 'json',
    success: function (response) {
        console.info(response);
    }
});
}

</script>

Give this method a try for handling JWT tokens with localstorage.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS: The dynamic setting for the stylesheet link tag initiates the request prematurely

I'm encountering a problem that is somewhat similar (although not exactly the same, so please be patient) to the one discussed in Conditionally-rendering css in html head I am dynamically loading a stylesheet using a scope variable defined at the sta ...

Deleting an element from an array in JavaScript by its index

I'm currently working on a todo type app and I need to figure out how to remove an array element. Adding elements using element.push() is straightforward, but removing them is a bit more challenging. The remove button is nested within a template liter ...

Problem encountered in servlet when downloading a Microsoft Word file from a Unix server to a Windows system

When I upload a doc file (such as test.doc) to a Unix server using the apache commons jar, I receive a FormFile instance at the server side containing the data in byte array form. However, when I write this byte array to the response output stream and sen ...

Custom container width causes animation to crash when scrolling

I'm having trouble with my header. When the containers change with scrolling, an animation takes place. Everything works fine with native Bootstrap CSS, but when I customize the width of the container in my custom CSS (the width set to 1140px), the an ...

Can angular and grunt support multiple run blocks simultaneously?

Currently, I am configuring $httpBackend to simulate fake API routes while our team of API developers is building them out. However, I am facing an issue where I have to place all the $httpBackend configurations within my run block. This leads to a situa ...

Guide on displaying a div upon clicking on a text box in asp.net with the help of jquery

I attempted it in this way: <script type="text/javascript"> $(document).ready(function () { $('#divID').hide(); $('#txtInsertComments').Onfocus(function () { $('#divID').show(); }); }); </script> //Asp.net ...

save choice in antd select in react js

In the process of developing a ReactJS project, I am utilizing the antd select component to display a list of companies. Upon selecting a company name, the users registered under that company will be shown. The attached video showcases the functionality fo ...

What steps should I follow to ensure that the content for the back page is printed on the back page of a booklet when using paged.js?

In the case of a booklet printed from folded sheets, it is interesting to note that the number on the back page will always be divisible by 4. If the content does not have a multiple of 4 pages, then the back page will end up inside the booklet. For my cu ...

The Embulk job encountered an issue when the embulk-output-bigquery plugin failed to process Korean characters within a JSON file

Our data processing setup includes the use of Embulk v0.8.13 plugin, embulk-input-redshift (0.7.4), and plugin embulk-output-bigquery (0.4.2) The job encountered a failure specifically when Korean characters were present in the JSON Error message: org. ...

Retrieving JQuery Results Based on List Items

Once I have obtained the list id from the navigation, my next step is to send the id to a PHP file that will return a JSON list. Below is the jQuery syntax I am using: $("#ul_navigation li").click(function(e) { idsec = this.id; alert(idse ...

Deserialization does not support the use of Type System.Collections.Generic.IDictionary for an array

An issue might arise when trying to call a page method using a manually created JQuery.ajax request. The deserialization process is handled by .NET and not within the user's code. Javascript: MyParam = []; ... $.ajax({ type: 'POST', ...

jQuery Form Plugin - fails to trigger error callback for Internal Server errors (500)

I am dealing with a situation where my server is returning a Status code 500, but my jQuery Form is triggering the success callback instead of the error callback. My current jQuery version is 1.7.1 and jQuery Form version is 2.73 from March 2011. The serv ...

Posting data to an HTML file with a foreign key matching the input value in Express.js

My discussion platform features topics and comments. Each comment has its own unique topic_id. Currently, I am able to post comments for the initial topic, but encountering issues when adding new comments for other topics. I am looking for guidance on effi ...

Is it possible to update the window title using javascript after a 3-second delay?

How can I alter the title bar of a window with a 3-second delay? This should be achieved using Javascript. www.nazeer.com ...

Adjusting the position of a stationary element when the page is unresponsive and scrolling

Managing a large web page with extensive JavaScript functionality can be challenging, especially when dealing with fixed position elements that update based on user scroll behavior. A common issue that arises is the noticeable jumping of these elements whe ...

Access the tapped region of an image on an Android device

Currently, I am developing a Quiz application that successfully displays normal questions in a TextView. I am now looking to incorporate images, such as identifying differences between two images or finding hidden letters within an image, where the user mu ...

Deciphering Google geocode output in Java - unable to locate JSONArray[0] (even though it exists)

UPDATE: I have encountered a problem with integrating a direction service program into my geocode project. Despite the code working separately, when combined, it throws an error consistently. (Using Eclipse, Java EE, and Tomcat7) For your reference, below ...

A guide on Extracting Values from Nested Objects

Although I am not well-versed in JavaScript, I have a small project where I need to use JavaScript. I am attempting to retrieve values from an object nested within another object. However, my code is throwing errors. Below is the snippet of my code with d ...

What is the best way to automatically log out a user once their session cookie has expired during an online exam?

While developing an MVC ExpressJS Test app, I encountered an issue with auto-logout functionality for users who stop answering test questions. The error message "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" keeps app ...

Having trouble with the copy to clipboard function of Prism JS on my NextJs application

I am facing an issue while trying to integrate a copy to clipboard plugin from prismjs into my next.js app. I have searched for documentation on this but couldn't find any relevant information. Despite going through various websites and implementing t ...