常见原因是未经身份验证的用户尝试访问受保护的资源,因此需要首先进行身份验证。如果使用AWS Amplify和React,可以使用Amplify组件和Auth实例进行身份验证。
以下是一种可能的解决方案:
import Amplify from 'aws-amplify';
Amplify.configure({
Auth: {
region: process.env.REACT_APP_COGNITO_REGION,
userPoolId: process.env.REACT_APP_COGNITO_USER_POOL_ID,
userPoolWebClientId: process.env.REACT_APP_COGNITO_APP_CLIENT_ID,
mandatorySignIn: true,
authenticationFlowType: 'USER_PASSWORD_AUTH'
}
});
import { Auth } from 'aws-amplify';
const signIn = async (email, password) => {
try {
const user = await Auth.signIn(email, password);
console.log('user:', user);
// 如果身份验证成功,则将用户存储在上下文中
// Redirect to protected resource
} catch (error) {
console.log('error:', error);
// Handle authentication errors
}
};
import { Auth } from 'aws-amplify';
const getUser = async () => {
try {
const user = await Auth.currentSession();
console.log('user:', user);
// 从用户场景中提取JWT令牌值
const token = user.getIdToken().getJwtToken();
console.log('token:', token);
} catch (error) {
console.log('error:', error);
// Handle authentication errors
// Redirect to login page
}
};