我正在使用 Nuxt 3 和 Pinia 为同一子域上的两个应用程序设置 SSO 登录,并将数据保存在 cookie 存储中。问题在于配置 cookie 的域选项,以便可以在不同子域上的两个应用程序之间访问它。
import { defineStore } from "pinia";
export const useAuthStore = defineStore(
"auth",
() => {
const loggedUser = ref("");
const hasPin = ref(false);
const language = ref(window?.navigator?.language);
const isLoggedIn = computed(() => !!loggedUser.value);
const refresh_token = computed(() => loggedUser?.value?.jwToken);
const access_token = computed(() => loggedUser?.value?.jwToken);
const roles = computed(() => loggedUser?.value?.roles);
const userId = computed(() => loggedUser?.value?.id);
const businessId = computed(() => loggedUser?.value?.businessId);
const userInfo = computed(() => loggedUser?.value);
function setLoggedUser(data) {
loggedUser.value = data;
cookie.value = data
}
function setHasPin(data) {
hasPin.value = data;
}
function setAccessToken(value) {
let userInfo = { ...loggedUser?.value, access_token: value };
setLoggedUser(userInfo);
}
function setRefreshToken(value) {
let userInfo = { ...loggedUser?.value, refresh_token: value };
setLoggedUser(userInfo);
}
function updateUser(value) {
let userInfo = { ...loggedUser?.value, fullName: value };
setLoggedUser(userInfo);
}
function updateAccountType(value) {
let userInfo = { ...loggedUser?.value, accountType: value };
setLoggedUser(userInfo);
}
function updateUserInfo(data) {
let userInfo = { ...loggedUser?.value, ...data };
setLoggedUser(userInfo);
}
const logOut = () => {
const authCookie = useCookie('auth')
localStorage.clear();
authCookie.value = null
window.location.href = "/auth/login";
};
return {
updateUser,
isLoggedIn,
refresh_token,
access_token,
roles,
userId,
userInfo,
setRefreshToken,
setAccessToken,
updateAccountType,
updateUserInfo,
setLoggedUser,
logOut,
loggedUser,
businessId,
language,
setHasPin,
hasPin,
};
},
{
persist: {
storage: persistedState.cookies,
},
}
);
我将代码添加到我的身份验证存储设置中,在底部您可以看到我将 cookie 指定为存储选项的位置
考虑到
persistedState.cookies
是 Nuxt useCookies
的包装器,domain
选项 需要使用 .
前缀传递,以便将 cookie 应用于域及其子域:
{
persist: {
storage: persistedState.cookies({ domain: '.mydomain.com' })
},
}