【发布时间】:2017-09-26 21:02:49
【问题描述】:
我正在尝试在 react-router 网站上复制 authenticating specific routes 的逻辑。在大多数情况下,它工作正常,但是当确定用户的逻辑本质上是异步的时,我在检查用户是否仍然被授权时似乎遇到了问题。下面列出的是我的私有路由的组件函数。
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
isAuthenticated() ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/login',
state: {from: props.location }
}}/>
)
)}/>
)
这个逻辑调用了我的 isAuthenticated 函数,该函数使用 Amazon Cognito 进行异步调用,它始终将 isAuthenticated 视为返回一个假值,即使我知道它应该返回一个真值。 isAuthenticated 的代码如下所示:
const isAuthenticated = () => {
var poolData = {
UserPoolId : 'XXX',
ClientId : 'XXXX'
};
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
var cognitoUser = userPool.getCurrentUser();
if (cognitoUser != null) {
cognitoUser.getSession(function(err, session) {
if (err) {
return false;
}
else{
return session.isValid();
}
});
}
else{
return false;
}
}
如果我只是硬编码 isAuthenticated 以返回 true 或 false 值,它在这两种情况下都能正常工作。我的问题是在这种情况下是否允许异步逻辑,或者我是否应该确定此逻辑上游的身份验证状态。
【问题讨论】:
标签: reactjs react-router amazon-cognito react-router-v4