Storing JSON Web Tokens (JWT) securely in Vuex state with the Nuxt Auth

While the login/logout/middleware functionalities are working, I am facing an issue with controlling the token. I am attempting to store the JWT in Vuex store after logging in, but it is only being saved in a cookie and localStorage. As per the documentation, auth support in Vuex should be added automatically. I didn't specify tokenRequired and tokenType in the config, which according to the documentation, are required for a cookie-based flow (even though adding them did not make a difference).

nuxt.config.js

modules: [
    '@nuxtjs/axios',
    '@nuxtjs/auth'
],
axios: {
    baseURL: 'https://api.example.com/'
},
router: {
    middleware: ['auth']
},
auth: {
    strategies: {
        local: {
            endpoints: {
                login: { url: 'login', method: 'post', propertyName: 'token' },
                logout: { url: 'logout', method: 'post' },
                user: false
            }
        }
    },
    redirect: {
        login: '/login',
        logout: '/',
        callback: '/login',
        home: '/'
    }
},

login function

await this.$axios.post('authenticate', {
    email: this.email,
    password: this.password
}).then(response => {
    if (response.success === 'true') {
        this.$auth.setUserToken(response.token)
    } else {
        //alert invalid login
    }
}).catch(error => {
    //alert server error
});

After successful login, when I check $auth.$state, it shows

{ "user": {}, "loggedIn": true, "strategy": "local" }

I was expecting the token to also be stored in $auth.

I came across a similar question on Stack Overflow, but the solution provided did not work for me since I have used user: false.

Answer №1

After examining the contents of the auth-module's default.js file, I made the decision to incorporate the default settings into my own nuxt.config.js. Once I made this adjustment to my configuration, everything started functioning seamlessly. This allowed me to successfully deactivate cookies and localStorage, choosing to store the JWT exclusively in the store.

auth: {
    strategies: {
        local: {
            endpoints: {
                login: { url: 'login', method: 'post', propertyName: 'token' },
                logout: { url: 'logout', method: 'post' },
                user: false
            }
        }
    },
    redirect: {
        login: '/login',
        logout: '/',
        callback: '/login',
        home: '/'
    },
    cookie: false,
    localStorage: false,
    token: {
        prefix: 'token.'
    },
},

Additionally, the output of $auth.$state is:

{ "user": {}, "loggedIn": true, "strategy": "local", "token.local": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ik.....}

<p>If anyone has any insights as to why the default configurations didn't work initially and had to be manually added to the setup, please feel free to share your thoughts. It appears that the saving functionality within Vuex may have been deliberately disabled by default, contradicting what the documentation suggests.</p>

<blockquote>
  <p>Auth tokens are stored in various storage providers (cookie, localStorage, vuex) </p>
</blockquote>
    </div></answer1>
<exanswer1><div class="answer accepted" i="56708184" l="4.0" c="1561128136" m="1561142425" a="Q3JheQ==" ai="11271432">
<p>Upon inspecting the <code>default.js file from the auth-module and applying the default values to my nuxt.config.js, the system began to function correctly. By doing so, I was able to turn off cookies and localStorage while only storing the JWT in the store.

auth: {
    strategies: {
        local: {
            endpoints: {
                login: { url: 'login', method: 'post', propertyName: 'token' },
                logout: { url: 'logout', method: 'post' },
                user: false
            }
        }
    },
    redirect: {
        login: '/login',
        logout: '/',
        callback: '/login',
        home: '/'
    },
    cookie: false,
    localStorage: false,
    token: {
        prefix: 'token.'
    },
},

The return value for $auth.$state is:

{ "user": {}, "loggedIn": true, "strategy": "local", "token.local": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" }

If there is an explanation as to why the default settings did not work initially and required manual inclusion in the configuration, I would appreciate any insights. Perhaps the automatic saving feature in Vuex was intentionally disabled by default, despite what the documentation indicates.

Auth tokens are stored in various storage providers (cookie, localStorage, vuex)

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

Troubleshooting and analyzing the performance of web workers

When running computations like path-finding in web workers, it can take several seconds and optimizing it is crucial. I've noticed that Chrome is roughly 3 times faster for my current code, but I'm not sure where exactly the time is being spent o ...

How can I resolve the issue of not returning anything ondrop in my code?

Whenever I drop my div containing an image, I don't see anything. And when I try to access its ID, I get a null value. How can I extract information from a div with an image and append a row with it? For code samples or to check the codepen example, v ...

Retrieve a file from a URL using Javascript's AJAX functionality

I have a CSV file uploaded to the server that I need to parse using JavaScript/jQuery. When trying to fetch the file with an AJAX call, I keep getting an error: XMLHttpRequest cannot load . No 'Access-Control-Allow-Origin' header is prese ...

Invoking AngularJS Function from Login Callback Script

Just getting started with angularjs and I have a logincallback function that is used for external login. This function returns the returnUrl, closes the externallogin pop up, and redirects back to the main page. function loginCallback(success, returnUrl) ...

Displaying entries of input data

I have an application that includes a modal window with filters, but I am looking to add another type of filter. However, I am struggling with implementing it in React and would appreciate any help with the code or recommended links. Essentially, I want t ...

Fluid sifting and interactive webpage

I'm almost done with my website, but I'm facing a problem. There are 3 blocks of text on my page - 2 static and 1 dynamic. When I click a button, the page should change, which is working fine. However, when I added smooth scroll to the website, ...

Transforming Attribute Directives into Elements in Angular 2

I've been trying to wrap my head around this Attribute Directive feature in Angular 2. Initially, I thought that directives could only be created using Attributes, but after some experimentation, I realized that I can also create directives using Ele ...

Using Javascript to choose an option from a dropdown menu

const salesRepSelect = document.querySelector('select[name^="salesrep"]'); for (let option of salesRepSelect.options) { if (option.value === 'Bruce Jones') { option.selected = true; break; } } Can someone please ...

What is the method for creating a new array of objects in Typescript with no initial elements?

After retrieving a collection of data documents, I am iterating through them to form an object named 'Item'; each Item comprises keys for 'amount' and 'id'. My goal is to add each created Item object to an array called ' ...

Steps to verify if a value is an integer:

Lately, I've been working on a "spinner" that increments and decrements a number by 1 each time. However, I'm struggling to add validation to the program so that it only accepts integers (no decimals). I've tried looking into NaN and parseVa ...

Incorporating a variety of functions into an external javascript file

I am currently working on enhancing the functionality of a basic HTML page by incorporating JavaScript with multiple buttons. The problem arises when I attempt to introduce another function in my external JS file, as it causes the existing code to stop wor ...

Issue with Ionic 2: Variable is altered but does not reflect in the HTML view

Hello everyone, I am new to the world of ionic 2 and I am facing a problem that I hope you can help me with. I have a variable that I want to display on my smartphone screen by placing it between {{ myVar }} in my HTML code. The initial display works fine, ...

"Troubleshooting: Ajax error 'Uncaught ReferenceError: data is not defined' on the

Upon checking the Chrome console, the error message displayed is : Uncaught ReferenceError: data is not defined function list(){ $.ajax({ type:'POST', url:'adeneme.php', data:$('#form1').seri ...

D3 - Rounded edge chart width

Currently facing an issue with the chart where the data value is small, resulting in an 'ear' effect. Can anyone help me with this problem? Below is the code I am currently using: const rx = 30; const ry = 30; svg ...

The map markers are nowhere to be found on the map when using Internet Explorer

Take a look at this code I wrote... var styles = [ { "featureType": "landscape", "stylers": [ {"weight": 0.1}, {"color": "#E7EDEF"} ] }, ... { "featureType": "poi.park", "elementType": "labels", "stylers": [ ...

Executing callback function within Observable.prototype.subscribe in Angular 2

Having issues with the complete callback not functioning as intended. Here's a breakdown: Take a look at this image and note the complete callback within the subscribe method. The complete function is only triggered when observerOrNext is called. If ...

Is there a way to modify the text color of table TD using Javascript?

I have experience with HTML/CSS, for example I can make text turn red using the code <table><tr><td style="color:#f00;">text</td>. However, I am struggling with JavaScript. When I try to change the color of a table cell u ...

Is it secure to use Vue Router for navigation?

I am currently working on a web project using Vue, and I have noticed that the following code snippet works when executed in the console: document.getElementById('app').__vue__.$router.push("some_route") Despite having meta tags define ...

Creating a JavaScript script to implement a CAPTCHA feature on Google Forms

I'm looking to implement a JavaScript solution that can prevent spam on Google Forms. The idea is as follows: Generate a random number a between 1 and 1000; Generate another random number b between 1 and 1000; Obtain input from the user, storing it a ...

The placement of the FirebaseAuth.onAuthStateChanged call in an Angular application is a common concern for developers

Where is the best place to add a global listener initialization call in an Angular app? Take a look at this code snippet: export class AuthService { constructor( private store: Store<fromAuth.State>, private afAuth: AngularFireAuth ) { ...