当应用程序与强制执行某种形式的身份验证的 HTTP API 进行通信时,应用程序通常会遵循以下步骤:
- 该应用程序未经过身份验证,因此我们提示用户登录。
- 用户输入其凭据(用户名和密码),然后点击提交。
- 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)_