React Native + Redux 基本身份验证

2024-05-27

我正在寻找一种为我的反应本机应用程序创建基本身份验证的方法。 我找不到任何反应本机应用程序的好例子。

  • 要登录,应用程序将电子邮件/密码 + clientSecret 发送到我的服务器
  • 如果OK,服务器返回accessToken+refreshToken
  • 用户已登录,所有其他请求都包含带有 accessToken 的承载。
  • 如果访问令牌过期,应用程序会自动使用刷新令牌请求新的访问令牌。
  • 用户始终保持登录状态,状态应保存在手机中。

最好的方法是什么?

Thanks.


当应用程序与强制执行某种形式的身份验证的 HTTP API 进行通信时,应用程序通常会遵循以下步骤:

  1. 该应用程序未经过身份验证,因此我们提示用户登录。
  2. 用户输入其凭据(用户名和密码),然后点击提交。
  3. We send these credentials to the API, and inspect the response:
    • On success (200 - OK): We cache the authentication token/ hash, because we're going to use this token/ hash in every subsequent request.
      • 如果令牌/哈希在任何后续 API 请求期间不起作用(401 - 未经授权),我们需要使哈希/令牌无效并提示用户再次登录。
    • 或者,失败时(401 - 未经授权):我们向用户显示一条错误消息,提示他们重新输入凭据。

在登录

根据上面定义的工作流程,我们的应用程序首先显示登录表单,step 2当用户点击登录按钮时启动,该按钮调度login下面的动作创建者:

/// actions/user.js

export function login(username, password) {
  return (dispatch) => {

    // We use this to update the store state of `isLoggingIn`          
    // which can be used to display an activity indicator on the login
    // view.
    dispatch(loginRequest())

    // Note: This base64 encode method only works in NodeJS, so use an
    // implementation that works for your platform:
    // `base64-js` for React Native,
    // `btoa()` for browsers, etc...
    const hash = new Buffer(`${username}:${password}`).toString('base64')
    return fetch('https://httpbin.org/basic-auth/admin/secret', {
      headers: {
        'Authorization': `Basic ${hash}`
      }
    })
    .then(response => response.json().then(json => ({ json, response })))
    .then(({json, response}) => {
      if (response.ok === false) {
        return Promise.reject(json)
      }
      return json
    })
    .then(
      data => {
        // data = { authenticated: true, user: 'admin' }
        // We pass the `authentication hash` down to the reducer so that it
        // can be used in subsequent API requests.

        dispatch(loginSuccess(hash, data.user))
      },
      (data) => dispatch(loginFailure(data.error || 'Log in failed'))
    )
  }
}

上面的函数中有很多代码,但请放心, 大部分代码正在清理响应并且可以被抽象掉。

我们做的第一件事是发送一个动作LOGIN_REQUEST它会更新我们的商店并让我们知道用户isLoggingIn.

dispatch(loginRequest())

我们用它来显示活动指示器(旋转轮、“正在加载...”等。),并禁用登录视图中的登录按钮。

接下来,我们对用户的用户名和密码进行 base64 编码以进行 http 基本身份验证,并将其传递到请求的标头。

const hash = new Buffer(`${username}:${password}`).toString('base64')
return fetch('https://httpbin.org/basic-auth/admin/secret', {
  headers: {
    'Authorization': `Basic ${hash}`
  }
/* ... */

如果一切顺利,我们将派出LOGIN_SUCCESS操作,这会导致我们进行身份验证hash在我们的商店中,我们将在后续请求中使用它。

dispatch(loginSuccess(hash, data.user))

另一方面,如果出现问题,我们也想让用户知道:

dispatch(loginFailure(data.error || 'Log in failed')

The loginSuccess, loginFailure, and loginRequest动作创建者相当通用,并不真正保证代码示例。看:https://github.com/peterp/redux-http-basic-auth-example/blob/master/actions/user.js) https://github.com/peterp/redux-http-basic-auth-example/blob/master/actions/user.js)_

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React Native + Redux 基本身份验证 的相关文章

随机推荐