我的用例是:
- 用户从我们的 API 请求资产,由于 JWT 过期而失败(作为 httpOnly cookie 传递) - API 返回 401 状态代码。
- 我们再次使用refresh_token对它们进行身份验证(无需用户执行任何操作),以通过客户端向auth0发出的请求检索新的JWT。
- 我们将该新 JWT 发送到我们的 API,将其设置为 httpOnly cookie 以替换过期的 cookie。
- 然后,我们要重试用户在步骤 1 中向 API 发出的原始请求。
我正在尝试在 Redux 应用程序中使用 Observablesredux-observable。如果您能想到另一种方法来使上述用户流程正常工作,我将很高兴听到如何做。
注意。我在用着rxjs V5
export const fetchAssetListEpic = (action$, store) => {
return action$.ofType('FETCH_ASSET_LIST')
.switchMap( action => {
const options = {
crossDomain: true,
withCredentials: true,
url: uriGenerator('assetList', action.payload)
};
return ajax(options);
})
.map(fetchAssetListSuccess)
.retryWhen(handleError)
.catch(redirectToSignIn);
};
function handleError(err) {
return (err.status === 401) ?
/* Authenticate here [Step 2] */
/* Send new JWT to API [Step 3] */
/* If successful make original request again [Step 4] */
:
Observable.throw(err);
}
function redirectToSignIn() {
/*I will redirect here*/
}
到目前为止,我能够完成步骤 1、2 和 3,但不太确定添加步骤 4 的方法。我可能完全偏离目标,但任何帮助都会很棒!
您可能不想做的一件事是允许错误进入顶级流。即使你做了一个catch
你已经有效地杀死了顶级流。因此,除非您的重定向是通过诸如反应路由器之类的东西进行硬重定向而不是软重定向,否则您将无法再使用这个史诗。
因此,我想说您希望将大部分逻辑封装在switchMap
:
function withAuthorizedFlow(source) {
return source
.map(fetchAssetListSuccess)
// retryWhen takes a callback which accepts an Observable of errors
// emitting a next causes a retry, while an error or complete will
// stop retrying
.retryWhen(e => e.flatMap(err =>
Observable.if(
// Returns the first stream if true, second if false
() => err.status === 401,
reauthenticate, // A stream that will emit once authenticated
Observable.throw(err) // Rethrow the error
))
)
.catch(redirectToSignIn);
}
/** Within the epic **/
.switchMap(({payload}) => {
const options = {
crossDomain: true,
withCredentials: true,
url: uriGenerator('assetList', payload)
};
// Invoke the ajax request
return ajax(options)
// Attach a custom pipeline here
// Not strictly necessary but it keeps this method clean looking.
.let(withAuthorizedFlow);
})
指某东西的用途let
上面是完全可选的,我把它放进去是为了清理函数。本质上,您希望将错误包含在内部流中,以便它无法停止外部流。我不确定是哪一个ajax
您正在使用的库,但您还应该确认它实际上会返回冷Observable
否则你需要将它包裹在一个defer
阻止为了retryWhen
上班。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)