需要在Amplify的Auth配置中正确设置允许未经身份验证的用户访问。具体示例代码如下:
import Amplify from 'aws-amplify';
import {AmplifyAuthenticator, withAuthenticator} from '@aws-amplify/ui-react';
Amplify.configure({
Auth: {
mandatorySignIn: true,
identityPoolId: 'YOUR_IDENTITY_POOL_ID',
region: 'YOUR_REGION',
userPoolId: 'YOUR_USER_POOL_ID',
userPoolWebClientId: 'YOUR_APP_CLIENT_ID',
authenticationFlowType: 'USER_PASSWORD_AUTH',
// 允许未经身份验证的用户访问
authenticationType: 'AMAZON_COGNITO_USER_POOLS',
clientMetadata: {}
}
});
// 使用withAuthenticator高阶组件来保护需要身份验证的组件
const ProtectedComponent = () => {
return (
只有登录后才能访问的组件!
)
}
export default withAuthenticator(ProtectedComponent);
需要注意,上面的代码示例中仅包含了必要的Auth配置项和一个受保护的组件,其他配置项和组件根据需要进行添加和修改。