Reactjs 在Redux Store中存储凭据是一种好做法?

Reactjs 在Redux Store中存储凭据是一种好做法?,reactjs,authentication,redux,access-token,Reactjs,Authentication,Redux,Access Token,我正在尝试开发一个React/Redux应用程序以供学习,我想知道我到目前为止所做的是一个好的实践还是不被推荐。 我必须处理的第一件事是处理授权请求。 我有一个restfull api Rails后端。此服务器响应附加在头参数(如访问令牌)中的登录请求。 此访问令牌仅对下一个请求有效,然后返回对下一个请求有效的新令牌,以此类推 我以这种方式实现了这个流程: 商店分派执行登录请求并传递用户名和密码的操作。然后,当响应就绪时,我将凭据存储在redux存储中。 当我需要执行授权请求时,我在头请求中设置

我正在尝试开发一个React/Redux应用程序以供学习,我想知道我到目前为止所做的是一个好的实践还是不被推荐。 我必须处理的第一件事是处理授权请求。 我有一个restfull api Rails后端。此服务器响应附加在头参数(如访问令牌)中的登录请求。 此访问令牌仅对下一个请求有效,然后返回对下一个请求有效的新令牌,以此类推

我以这种方式实现了这个流程: 商店分派执行登录请求并传递用户名和密码的操作。然后,当响应就绪时,我将凭据存储在redux存储中。 当我需要执行授权请求时,我在头请求中设置这些参数。 当我收到响应时,我会使用从响应中获得的新凭据更新存储中的凭据

以下是我的代码,以获得更清晰的信息:

import { combineReducers } from 'redux'
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

const initialState = {
  currentUser: {
    credentials: {},
    user: {}
  },
  test: {},
  users: []
}

export const SUBMIT_LOGIN = 'SUBMIT_LOGIN'
export const SET_USER = 'SET_USER'
export const TEST = 'TEST'
export const SET_USERS = 'SET_USERS'
export const SET_CREDENTIALS = 'SET_CREDENTIALS'

//actions
const submitLogin = () => (dispatch) => {
  return postLoginRequest()
    .then(response => {
      dispatch(setCredentials(
        response.headers.get('access-token'),
        response.headers.get('client'),
        response.headers.get('expiry'),
        response.headers.get('token-type'),
        response.headers.get('uid')
      ));
      return response
    })
    .then(response => {
      return response.json();
    })
    .then(
      (user) => dispatch(setUser(user.data)),
    );
}

const performRequest = (api) => (dispatch) => {
  return api()
    .then(response => {
      dispatch(setCredentials(
        response.headers.get('access-token'),
        response.headers.get('client'),
        response.headers.get('expiry'),
        response.headers.get('token-type'),
        response.headers.get('uid')
      ));
      return response
    })
    .then(response => {return response.json()})
    .then(json => {console.log(json)})
}

const setUsers = (users) => {
  return {
    type: SET_USERS,
    users
  }
}

const setUser = (user) => {
  return {
    type: SET_USER,
    user
  }
}

const setCredentials = (
  access_token,
  client,
  expiry,
  token_type,
  uid
) => {
  return {
    type: SET_CREDENTIALS,
    credentials: {
      'access-token': access_token,
      client,
      expiry,
      'token-type': token_type,
      uid
    }
  }
}

const currentUserInitialState = {
  credentials: {},
  user: {}
}

const currentUser = (state = currentUserInitialState, action) => {
  switch (action.type) {
    case SET_USER:
      return Object.assign({}, state, {user: action.user})
    case SET_CREDENTIALS:
      return Object.assign({}, state, {credentials: action.credentials})
    default:
      return state
  }
}

const rootReducer = combineReducers({
  currentUser,
  test
})

const getAuthorizedHeader = (store) => {
  const credentials = store.getState().currentUser.credentials
  const headers = new Headers(credentials)
  return headers
}

//store creation

const createStoreWithMiddleware = applyMiddleware(
  thunk
)(createStore);

const store = createStoreWithMiddleware(rootReducer);

const postLoginRequest = () => {
  return fetch('http://localhost:3000/auth/sign_in', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      email: 'test@test.com',
      password: 'password',
    })
  })
}

const getUsers = () => {
  const autorizedHeader = getAuthorizedHeader(store)
  debugger
  return fetch('http://localhost:3000/users',
    {
      method: 'GET',
      headers : autorizedHeader
    }
  )
}


store.dispatch(submitLogin())

setTimeout(() => {
  console.log(store.dispatch(performRequest(getUsers)))
}, 2000)
我想知道在商店中存储合理的数据是否是一种良好的做法,如果不是,我愿意接受任何以更好的方式开发此工作流的建议

我的服务器上也有这个参数

config.batch_request_buffer_throttle = 5.seconds
有时需要同时向API发出多个请求。在这种情况下,批处理中的每个请求都需要共享相同的身份验证令牌。此设置确定在仍然使用同一身份验证令牌的情况下请求之间的距离

这样,如果令牌仍然有效,我就无法在performRequest函数中调度setCredentials操作,但我真的不知道如何检查它


谢谢

不,这不是一个好的练习。如果您希望更好地存储用户会话,请使用cookie会话来存储JWT,以备React.js使用

如果使用react native来存储您的密码,我也建议将其作为JWT令牌或加密文本,而不是纯文本

您的实现主要取决于后端。如果您使用诸如node.js服务器之类的库,则使用crypt令牌来授权请求。但是,不管你用什么方法进行身份验证,都不要将它简单地存储在状态中。

使用将对你有所帮助

原因当您在Redux存储中获取身份验证数据时,如果页面刷新或历史记录移动(后退| |前进),则存储值不再存在。刷新后,应用程序将请求验证数据。。刷新

使用
窗口。会话存储可以在刷新或移动历史记录后保留数据


  [AFTER LOGIN EVENT]

    window.sessionStorage.setItem(key,vlaue)

  [AFTER LOGOUT EVENT]

    window.sessionStorage.clear() <- removes all records in sessionStorage.
    window.sessionStorage.removeItem(key) 


[登录事件后]
window.sessionStorage.setItem(键,vlaue)
[注销事件后]

window.sessionStorage.clear()Redux存储在内存中(除非您将其存储在其他地方)。如果是这种情况,则重新加载页面后凭证和/或会话将立即丢失。听起来很合理,但我觉得不太合理。对于手机或单页应用程序,用户“重新加载页面”可能需要几周的时间,而在这段时间里,他的凭证都存储在内存中的某个地方。听起来像是一个可能的漏洞。@VaclavSir那么你的解决方案是什么呢?我同意@AndreyLuiz的说法。将令牌/凭据放在localStorage中,并在需要发出服务器请求时检查localStorage中的凭据。如果凭据不再存在或无效,请从存储中删除所有内容并执行注销操作。在您的reducer中,注销操作应返回空状态,以便有关上一个会话的所有信息也从状态中删除。如果您确实希望确保没有人使用凭据过期的应用程序,还可以在localStorage中对凭据进行定期检查,以确保凭据已过期valid@JoeyGough任何站点都可以访问您的本地存储,但本地存储是基于域的。因此,如果网站www.abc.com在您的本地存储中保存了任何内容,当您访问www.def.com时,它将无法访问www.abc.com已保存的任何信息。我不建议使用此方法存储凭据。这是不安全的。你能详细说明原因吗?您看到的缺点/安全问题是什么?