What is the best place to keep my JWT token secure?

Currently, I am working on an application using vue.js and vuex that authenticates to a JSON API server through JWT tokens. The challenge I'm facing is determining the best method for storing the JWT token securely.

If I choose to store the token in the vuex store, it unfortunately gets cleared after the page is refreshed, leading to users needing to log in again, which is not an ideal user experience.

Alternatively, if I opt to store the JWT token in local storage within the browser, it becomes deprecated before the next login session, causing confusion among components relying on the authentication token. This ongoing issue has left me unsure of how best to address it.

I would greatly appreciate any insights or suggestions you may have on this matter. Thank you!

Answer №1

During my work on a react project utilizing the axios library, I encountered a similar issue. Upon receiving a 401 (Unauthenticated) response from the server, I took steps to obtain a new JWT token by using a separate token known as refreshToken which had no expiration date.

axios.interceptors.response.use(
    ok => ok,
    err => {
        if(err.response.status === 401) {
            return axios
                    .get('/api/oauth/token/refresh', {
                        headers: {'Authorization': `Bearer ${localStorage.getItem('refreshToken') }`}
                    })
                    .then(({data}) => {
                        // The newly obtained access token is found in data
                        err.config.headers['Authorization']=`Bearer ${data.token}`;
                        return axios(err.config)
                    });

        } 

        throw err
    }
);

Answer №2

When I save data in the local storage of the browser, it often becomes deprecated before the next login, causing confusion for components relying on the authentication token. I am unsure how to address this issue.

Contrary to popular belief, localStorage information is stored per Document origin. It is up to the application to verify if the token is still valid (not expired) and redirect the user to the Login page if necessary.

It is important to adjust the expiration period to allow for reasonable relogin times, and implement a reliable algorithm for extending the JWT token. For example, you could automatically extend the login duration by 1 day every time a user makes a request to the server and has only 1 hour left on their current token.

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

What is the process of updating values in an object that is part of an array?

I am currently facing an issue where I am attempting to implement an edit function to replace text and dates. While I have managed to successfully update the text using the DOM, the edited values revert back to their original form upon page refresh. I susp ...

Can Vuetify components be resized?

After incorporating Vuetify into my UI designs, I noticed that the default input components like v-text-field and v-select appear too large. While I was able to adjust their width, I'm unsure how to change the height and font size. Any advice on how t ...

Encountering an 'Unknown provider' error while running a unit test with AngularJS and Jasmine

I am facing an issue while writing a unit test for a controller in my application. Jasmine is showing an 'Unknown provider' error related to a provider I created for fetching template URLs. This provider is injected into a config function that is ...

What are the troubleshooting tools available in Electron for detecting errors and debugging issues?

What is the process for accessing error messages and console logs in Electron while developing? Can the logs be saved directly to a file as well? Edit: Similar to how error messages and console logs are shown in Chrome's dev tools, but within Electro ...

Exploring the power of Firebase with Vue Js lifecycle methods

I am attempting to retrieve data from a specific user in Firebase and push that data into designated input fields. The path in Firebase is located here: var query = db.ref('Clients/'+ clientName +'/form/'); I retrieve the data in the ...

Enter your password using the text input field on Internet Explorer 8

I'm currently developing a website and facing an issue with the password input field: When clicking on it in browsers like IE9, Chrome, and Mozilla, the text changes to allow entry of the password. However, in IE8, clicking on the input field leaves ...

The fastest method for finding the longest palindrome subsequence within a given string

I've been working on creating a function that can identify the longest palindrome subsequence within a given string. After experimenting with dynamic programming, I came up with the code snippet below: function findLongestPalindrome(str) { let lengt ...

bind a class property dynamically in real-time

I need to dynamically generate a TypeScript class and then add a property to it on the go. The property could be of any type like a function, Promise, etc., and should use this with the intention that it refers to the class itself. let MyClass = class{ ...

JavaScript has the ability to manipulate the width of an element by using methods to both retrieve

I have a unique situation where I need to dynamically adjust the width of a ul list element based on the text content inside it. Specifically, I want the width of the ul list to be equal to the width of the first list item, which can change frequently. My ...

JS/PHP: No error message will be alerted

<script type="text/javascript"> $(function() { $("#continue").click(function () { $.ajax({ type: "POST", url: "dbc.php?check=First", data: {full_name : $('#full_name').val(), usr_email : $('#usr_ema ...

Run the GetServerSideProps function every time the button is clicked

Struggling with my NextJS app development, I encountered an issue while trying to fetch new content from an API upon clicking a button. The server call is successful, but the update only happens when I refresh the page rather than triggering it with the bu ...

Issue with component not updating despite waiting for react context

I'm troubleshooting why the page isn't re-rendering once isFetchingData is set to false. I have a useEffect in the context and expect it to trigger a re-render when isFetchingData changes. Any suggestions? Refreshing the page displays the data, ...

What steps should I follow to ensure that the processData function waits for the data returned by the getData function in Angular?

After calling the getData function, each object is stored in an array and returned. Now I need the processData function to await these results from getData and then further process them. However, when I try to console.log(cleaningData), I don't see an ...

What is the reason behind the cautionary note associated with Vue's provide and inject functionality?

Considering incorporating Vue's new provide/inject feature into a project, I came across a warning in the official Vue documentation: The documentation states that provide and inject are primarily intended for advanced plugin/component library usage ...

Creating a fresh JSON structure by utilizing an established one

I have a JSON data that contains sections and rubrics, but I only need the items for a new listing. The new object named 'items' should consist of an array of all the items. The final JSON output should be sorted by the attribute 'name&apos ...

How can JavaScript effectively retrieve the JPEG comment from a JPEG file?

How can one properly retrieve the JPEG comment field (not EXIF, but the COM field) from a JPEG file using JavaScript, particularly when running node on the command line? While there are several libraries available for reading EXIF data in JavaScript, I ha ...

Child component emitting a Vue.js event fails to transmit it to the parent component

Within my vue.js application, I have a component containing children of either type "Test" or "AnotherComponent". The user has the ability to add one of these components by clicking a button, which will then be appended to the end of the list of child comp ...

Combining a standard JSS class with Material-UI's class overrides using the classnames library

I am exploring the method of assigning multiple classes to an element in React by utilizing the classnames package from JedWatson, along with Material-UI's "overriding with classes" technique. For reference, you can see an instance in MUI's docu ...

Unable to establish a local dependency link with npm

Attempting to connect my local project testabc123 to myproject using the usual method: cd testabc123 npm link cd ../myproject npm link testabc123 However, encountering an error message: npm ERR! code E404 npm ERR! 404 Not Found - GET http://registry.npmjs ...

In TypeScript, the first element of an array can be inferred based on the second element

Let's consider a scenario where we have a variable arr, which can be of type [number, 'number'] or [null, 'null']. Can we determine the type of arr[0] based on the value of arr[1]? The challenge here is that traditional function ov ...