您好,我想将 JWT 令牌保存在 HttpOnly cookie 中。成功登录后从 django 后端收到令牌。
一切正常,直到我在 pinia 商店中添加 HttpOnly 标志。
如何将令牌安全地存储在前端?
Pina auth.js 商店:
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,
})
}
})
中间件 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('/')
}
})
登录页面的登录功能
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('/')
}
},
})
}
尝试了不同的方式来存储和访问cookie。
要将令牌安全地存储在前端,请尝试 localStorage 或 cookie 设置,假设您的令牌具有 access 和 refreshToken 作为属性,请在 pinia 存储中添加:
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 和 this.refreshToken 是必须在商店状态中定义的字符串,$config.token 和 $config.refreshToken 可以在
nuxt.config.ts
中定义,如下所示:
runtimeConfig: {
public: {
token: 'PROJECT_NAME_TOKEN',
refreshToken: 'PROJECT_NAME_REFRESH_TOKEN'
}
}
“PROJECT_NAME_TOKEN”、“PROJECT_NAME_REFRESH_TOKEN”将是您浏览器 cookie 中的令牌和刷新令牌的密钥
根据项目数据调整名称和代币对象