如何在没有刷新令牌的情况下使用 RTK 查询保持用户登录状态

问题描述 投票:0回答:1

我是第一次使用 RTK 查询,我想在刷新页面时保持用户登录状态。

我正在处理一个不会使访问令牌过期的端点(它会持续一年左右),因此没有刷新令牌可供使用或任何东西,只有访问令牌(我知道,这对于安全性来说很糟糕,但是我对此无能为力)。

那么,我应该将访问令牌存储在 localStorage 还是 Cookie 中?我知道不建议这样做,但我不知道该怎么办。

如有任何帮助或指南链接,我们将不胜感激。

这是我的 authApiSlice 代码...

import { MetadataObj } from '../../../types/globalTypes';
import { apiSlice } from '../../app/api/apiSlice';
import { logOut } from './authSlice';

export const authApiSlice = apiSlice.injectEndpoints({
  endpoints: builder => ({
    login: builder.mutation({
      query: (credentials: MetadataObj) => ({
        url: "/signin",
        method: "POST",
        body: { ...credentials },
      }),
    }),
    sendLogout: builder.mutation({
      query: () => ({
        url: "/logout",
        method: "POST",
      }),
      async onQueryStarted(arg, { dispatch, queryFulfilled }) {
        try {
          await queryFulfilled;
          dispatch(logOut(null));
          dispatch(apiSlice.util.resetApiState());
        } catch (err) {
          console.log(err);
        }
      },
    }),
  }),
});

export const { useLoginMutation, useSendLogoutMutation } = authApiSlice;
authentication persistence rtk-query
1个回答
1
投票

一般来说,您有两种选择:

  1. 将访问令牌存储在(本地存储/cookie)中,并在需要时从那里读取。

  2. 将访问令牌存储在 redux 中并保留该 redux 状态!

如您所知,redux 状态不会持续存在,当您刷新页面时,您的 redux 下次将为空。对于第二种方法,您必须在 Redux 存储中设置 redux-persist 并与工具包集成(redux 工具包持久文档)。

这也可以帮助: 如何使用redux-toolkit配置redux-persist?

顺便说一句,我更喜欢第一种方法。

© www.soinside.com 2019 - 2024. All rights reserved.