我正在做一个项目,但我想知道如果我已经在我们的应用程序中使用了 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;
答案 0 :(得分:1)
您可以将其保留在商店中,您还应该为令牌过期设置超时,以便在令牌过期后注销用户。
我添加了一个包,让您可以解码令牌以检索令牌的 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 存储中,而是保存到 localStorage 中,您可以在需要的地方从存储中读取并传递它。
答案 1 :(得分:0)
这样你就必须在每次刷新时发送登录请求,就像每次页面重新加载 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))
);