ale*_*ngn 24 javascript authentication react-native redux
我正在寻找一种为我的react-native应用程序创建基本身份验证的方法.我找不到react-native app的任何好例子.
对此最好的方法是什么?
谢谢.
pet*_*erp 57
当应用程序与强制执行某种形式身份验证的HTTP API进行通信时,应用程序通常会遵循以下步骤:
根据上面定义的工作流程,我们的应用程序首先显示一个登录表单,当用户点击下面调度动作创建者的登录按钮时,第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'))
)
}
}
Run Code Online (Sandbox Code Playgroud)
上面的函数中有很多代码,但是大多数代码都在清理响应并且可以将其抽象出来.
我们要做的第一件事是发送一个动作LOGIN_REQUEST来更新我们的商店并让我们知道该用户isLoggingIn.
dispatch(loginRequest())
Run Code Online (Sandbox Code Playgroud)
我们使用它来显示活动指示器(旋转轮,"正在加载..."等),并在我们的登录视图中禁用登录按钮.
接下来,我们base64编码用户的http basic auth的用户名和密码,并将其传递给请求的标头.
const hash = new Buffer(`${username}:${password}`).toString('base64')
return fetch('https://httpbin.org/basic-auth/admin/secret', {
headers: {
'Authorization': `Basic ${hash}`
}
/* ... */
Run Code Online (Sandbox Code Playgroud)
如果一切顺利,我们将发送一个LOGIN_SUCCESS动作,这导致我们hash在我们的商店中进行身份验证,我们将在后续请求中使用.
dispatch(loginSuccess(hash, data.user))
Run Code Online (Sandbox Code Playgroud)
另一方面,如果出现问题,我们也想让用户知道:
dispatch(loginFailure(data.error || 'Log in failed')
Run Code Online (Sandbox Code Playgroud)
的loginSuccess,loginFailure和loginRequest动作的创造者是很普通的,并不能真正保证代码样本.请参阅:https://github.com/peterp/redux-http-basic-auth-example/blob/master/actions/user.js)
我们的减速机也很典型:
/// reducers/user.js
function user(state = {
isLoggingIn: false,
isAuthenticated: false
}, action) {
switch(action.type) {
case LOGIN_REQUEST:
return {
isLoggingIn: true, // Show a loading indicator.
isAuthenticated: false
}
case LOGIN_FAILURE:
return {
isLoggingIn: false,
isAuthenticated: false,
error: action.error
}
case LOGIN_SUCCESS:
return {
isLoggingIn: false,
isAuthenticated: true, // Dismiss the login view.
hash: action.hash, // Used in subsequent API requests.
user: action.user
}
default:
return state
}
}
Run Code Online (Sandbox Code Playgroud)
现在我们在商店中有一个身份验证哈希,我们可以将它传递给后续请求的头文件.
在下面的示例中,我们为经过身份验证的用户提取了一个朋友列表:
/// actions/friends.js
export function fetchFriends() {
return (dispatch, getState) => {
dispatch(friendsRequest())
// Notice how we grab the hash from the store:
const hash = getState().user.hash
return fetch(`https://httpbin.org/get/friends/`, {
headers: {
'Authorization': `Basic ${hash}`
}
})
.then(response => response.json().then(json => ({ json, response })))
.then(({json, response}) => {
if (response.ok === false) {
return Promise.reject({response, json})
}
return json
})
.then(
data => {
// data = { friends: [ {}, {}, ... ] }
dispatch(friendsSuccess(data.friends))
},
({response, data}) => {
dispatch(friendsFailure(data.error))
// did our request fail because our auth credentials aren't working?
if (response.status == 401) {
dispatch(loginFailure(data.error))
}
}
)
}
}
Run Code Online (Sandbox Code Playgroud)
您可能会发现大多数API请求通常会调度与上述相同的3个操作:API_REQUEST,API_SUCCESS和API_FAILURE,因此大多数请求/响应代码都可以推送到Redux中间件.
我们从商店获取哈希认证令牌并设置请求.
const hash = getState().user.hash
return fetch(`https://httpbin.org/get/friends/`, {
headers: {
'Authorization': `Basic ${hash}`
}
})
/* ... */
Run Code Online (Sandbox Code Playgroud)
如果API响应带有401状态代码,那么我们必须从商店中删除我们的哈希,并再次向用户显示日志.
if (response.status == 401) {
dispatch(loginFailure(data.error))
}
Run Code Online (Sandbox Code Playgroud)
我一般都回答了这个问题,只处理了http-basic-auth.
我认为,这个概念可以保持不变,你会推accessToken和refreshToken在商店,并在后续请求中提取出来.
如果请求失败,那么您将不得不分派另一个更新accessToken的操作,然后调用原始请求.
| 归档时间: |
|
| 查看次数: |
16144 次 |
| 最近记录: |