【问题标题】:How to implement auth in front-end with Redux?如何使用 Redux 在前端实现身份验证?
【发布时间】:2019-11-04 16:17:56
【问题描述】:

我想知道前端的身份验证过程(如何以及在哪里保存令牌,如何检查用户是否登录等),当他们尝试访问登录页面时重定向到登录页面需要等。

我不想要这个的实现,只需要帮助我的库,如果要保存令牌之类的东西,我应该把它保存在哪里?

我目前正在学习Redux,知之甚少,我也看过一篇关于Saga的文章,好像对这个认证过程很有用。

至于后端,我基本上需要安装一些 Django 扩展,并且我将拥有一些端点,例如:输入用户名/密码并返回访问令牌、使访问令牌过期、注册用户、重置密码等。

现在我知道我需要 Redux 并使用 react-router 的 Provider 和 Router。还有关于 action、reducers、store 等的基础知识。但仅此而已。

重要提示:我打算使用钩子而不是类组件。

【问题讨论】:

标签: reactjs authentication redux redux-saga


【解决方案1】:

简短说明:

我建议你使用 JWT 进行身份验证,你应该将令牌保存在 localStorage 中

当您登录/注册服务器响应 jwt-token 时:

localStorage.setItem('usertoken', token)

然后你应该检查用户身份验证:

const isAuth = localStorage.getItem('usertoken')

如果你使用 react-router-4:

if (!isAuth) {
  return <Router render={() => <Redirect to="/login" />}
}

// ...your protected routes

此外,每个 api 请求都应在 api.js 文件中包含一个 jwt-token:

const apiResponse = await fetch(url, {
   ...someOptions,
   headers: { 'x-access-token': localStorage.getItem('usertoken') }
})

如果服务器返回 401 响应,您应该删除令牌:

if (response.status === 401) {
    localStorage.removeItem('usertoken');

    window.location.href = '/login';
}

auth 使用 cookie 的另一种方式

【讨论】:

    猜你喜欢
    • 2019-03-25
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    相关资源
    最近更新 更多