要使用 JWT 令牌在AppSync Amplify中进行身份验证,您可以按照以下步骤操作:
npm install aws-amplify @aws-amplify/api @aws-amplify/auth
import Amplify from 'aws-amplify';
import API from '@aws-amplify/api';
import Auth from '@aws-amplify/auth';
Amplify.configure({
Auth: {
region: 'YOUR_AWS_REGION',
userPoolId: 'YOUR_USER_POOL_ID',
userPoolWebClientId: 'YOUR_USER_POOL_CLIENT_ID',
mandatorySignIn: true,
},
API: {
endpoints: [
{
name: 'YOUR_API_NAME',
endpoint: 'YOUR_API_ENDPOINT',
custom_header: async () => {
return {
Authorization: `Bearer ${(await Auth.currentSession()).getIdToken().getJwtToken()}`,
};
},
},
],
},
});
在上面的代码中,您需要将YOUR_AWS_REGION
,YOUR_USER_POOL_ID
,YOUR_USER_POOL_CLIENT_ID
,YOUR_API_NAME
和YOUR_API_ENDPOINT
替换为实际的值。
Auth.signIn('USERNAME', 'PASSWORD')
.then(() => {
API.get('YOUR_API_NAME', '/your/api/path')
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
})
.catch(error => {
console.error(error);
});
在上面的代码中,您需要将USERNAME
和PASSWORD
替换为实际的用户名和密码,YOUR_API_NAME
和/your/api/path
替换为实际的API名称和路径。
通过这些步骤,您可以使用JWT令牌进行AppSync Amplify应用程序的身份验证。请确保您已正确配置AWS Cognito和AppSync端点。