Shirony
Shirony

Reputation: 54

Nuxt Middleware | httpOnly Cookie after page reload gone

Hello i want to save a JWT token in an HttpOnly cookie. The token is received from a django backend after successful login.

Everything works fine until i add the HttpOnly flag in the pinia store.

How can i store the token securely in the frontend?

Pina auth.js store:

import { defineStore } from 'pinia'

export const useAuthStore = defineStore({
    id: 'auth',
    state: () => ({
        user: {
            isAuthenticated: false,
            token: null
        }
    }),

    actions: {
        initStore() {
            // this.isAuthenticated = false
        },

        setToken(token) {
            this.user.token = token
            this.user.isAuthenticated = true
        },
        
        removeToken() {
            this.user.token = null
            this.user.isAuthenticated = false
        }
    },

    persist: {
        storage: persistedState.cookiesWithOptions({
            sameSite: 'strict',
            httpOnly: true,
            // secure: true,
        })
    }
})

Middleware auth.global.ts

import { useAuthStore } from "~/stores/auth"

export default defineNuxtRouteMiddleware((to, from) => {
    const authStore = useAuthStore()

    if (to.path !== '/login' && !authStore.user.isAuthenticated) {
        return navigateTo('/login')
      }

    if (to.path === '/login' && authStore.user.isAuthenticated) {
        return navigateTo('/')
    }
})

Login function from login page

async function submit() { 
    await useFetch('auth/jwt/create', {
        method: 'POST',
        baseURL: 'http://127.0.0.1:8000/',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(loginData),
        onResponseError({response}) {
            console.log('Error: ' + response.status)
        },
        onResponse({ response }) {
            if (response._data.access) {
                authStore.setToken(response._data.access)
                authStore.user.isAuthenticated = true
                navigateTo('/')
            }
        },
    })
}

Tried different ways of storing & accessing the cookies.

Upvotes: 3

Views: 343

Answers (1)

elham zeinodini
elham zeinodini

Reputation: 70

To store the token on the frontend , try the localStorage or cookie setup,assuming your token has access and refreshToken as properties, in your pinia store add:

 setAuthCookie(tokens: { access: null | string; refresh: null | string }{
  const { $config } = useNuxtApp()
  const token = useCookie($config.token)
  const refreshToken = useCookie($config.refreshToken)

  token.value = this.token = tokens.access
  refreshToken.value = this.refreshToken = tokens.refresh
},

clearAuthCookie() {
  this.setAuthCookie({ access: null, refresh: null })
},

this.token and this.refreshToken are strings that must be defined in your store's states, $config.token and $config.refreshToken can be defined in nuxt.config.ts like this:

runtimeConfig: {
   public: {
     token: 'PROJECT_NAME_TOKEN',
     refreshToken: 'PROJECT_NAME_REFRESH_TOKEN'
   }
}

the 'PROJECT_NAME_TOKEN' , 'PROJECT_NAME_REFRESH_TOKEN' are gonna be the keys of your token and refreshToken in your browser's cookie

adjust the names and the token object based on your project's data

Upvotes: 0

Related Questions