【问题标题】:Is it safe to store JWT token in redux store?将 JWT 令牌存储在 redux 存储中是否安全?
【发布时间】:2021-09-26 01:52:22
【问题描述】:

我正在做一个项目,但我想知道如果我已经在我们的应用程序中使用了 redux,那么我们可以停止使用 httponly cookie 来存储令牌吗?

这是我的减速器,我以这种方式将令牌存储在减速器中。而且我还使用 redux-persist 在用户重新加载页面时持久化用户。

那么,最好像这样存储 jwt 令牌?

import * as types from "./user.types";

const initialState = {
  token: null,
  user: {},
  loading: false,
  error: null,
};

const authReducer = (state = initialState, action) => {
  switch (action.type) {
    case types.LOGIN_START:
      return {
        ...state,
        loading: true,
      };
    case types.LOGIN_SUCCESS:
      return {
        ...state,
        loading: false,
        token: action.payload.jwt,
        user: action.payload.user,
      };
    case types.LOGIN_FAIL:
      return {
        ...state,
        loading: false,
        error: action.payload,
      };
    default:
      return state;
  }
};

export default authReducer;

【问题讨论】:

    标签: reactjs redux jwt


    【解决方案1】:

    这样你必须在每次刷新时发送登录请求,就像每次页面重新加载一样,redux store 也重新加载。

    最好将令牌保存在本地存储中,并将 redux 存储作为初始值拉入,以便每次重新加载时自动保存。

    店内:

    import { applyMiddleware, combineReducers, compose, createStore } from "redux";
    const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;  //for redux extension
    
            const initialState = {
                token: {
                token: localStorage.getItem("token")
                  ? JSON.parse(localStorage.getItem("token"))
                  : null,
              },
            };
        
        const store = createStore(
          reducer,
          initialState,
          composeEnhancer(applyMiddleware(thunk))
        );
    

    【讨论】:

    • 但是我用 redux-persist 实现了同样的目标。所以,我认为这里不需要 localStorage 。但无论如何,也感谢这个解决方案
    【解决方案2】:

    您可以将其保存在商店中,您还应该为令牌过期设置超时,一旦令牌过期,将注销用户。 我添加了一个包,让您可以解码令牌以检索令牌的 exp 到期时间,您可以将其更改为使用 redux-persist

    import jwt_decode from "jwt-decode";
    
    const token = localStorage.getItem('token')
    
    const initialState = {
      token: null,
      user: {},
      loading: false,
      error: null,
    };
    
    if(token) {
      try {
        const jwt_decoded = jwt_decode(token)
        const timeToExpire = jwt_decoded.exp - Date.now()
        if(timeToExpire > 0) {
          setTimeout(() => {
            // dispatch action to logout
          }, timeToExpire);
          initialState.token = token;
        } 
      } catch (error) {
        console.log("error parsing token")
      }
    }
    
    const authReducer = (state = initialState, action) => {
     // your reducer code here
    };
    

    注意:实际上不需要将它存储在redux store中,而是保存到localStorage,在需要的地方你可以从storage中读取并传递它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-19
      • 1970-01-01
      • 2020-10-30
      • 1970-01-01
      • 2019-02-01
      • 2015-09-15
      • 2016-09-13
      • 2020-05-27
      相关资源
      最近更新 更多