我正在尝试使用具有自定义身份验证角色的联合身份使用AWS AppSync API,但没有成功。
首先,我遵循此tutotial创建客户。然后,我打开联合身份控制台->编辑身份池->自定义并创建一个Developer provider name
:login.mycompany.myapp
并选中Enable access to unauthenticated identities
。
之后,我遵循此one来了解如何创建自定义身份验证。
一旦您从后端获取了身份ID和会话令牌, 您将把它们传递到AWS.CognitoIdentityCredentials 提供者。这是一个示例:
AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: 'IDENTITY_POOL_ID', IdentityId: 'IDENTITY_ID_RETURNED_FROM_YOUR_PROVIDER', Logins: { 'cognito-identity.amazonaws.com': 'TOKEN_RETURNED_FROM_YOUR_PROVIDER' } });
如何获得IDENTITY_ID_RETURNED_FROM_YOUR_PROVIDER
,cognito-identity.amazonaws.com
和IDENTITY_ID_RETURNED_FROM_YOUR_PROVIDER
?我看到了怎么做:
您可以通过调用GetOpenIdTokenForDeveloperIdentity获得令牌。必须使用AWS开发人员凭证从您的后端调用此API。
我检查了GetOpenIdTokenForDeveloperIdentity
documentation并创建了这段代码:
const AWS = require('aws-sdk');
AWS.config.region = 'us-east-1'; // Region
const cognitoidentity = new AWS.CognitoIdentity();
const params = {
IdentityPoolId: IDENTITY_POOL_ID',
Logins: {
'login.mycompany.myapp': 'sometoken',
},
};
cognitoidentity.getOpenIdTokenForDeveloperIdentity(params, function(
err,
{ IdentityId, Token }
) {
if (err) {
console.log(err);
}
console.log(IdentityId, Token);
}
我得到了IdentityId
和Token
。我采用了这些变量并创建了一个Cognito客户端,如下所示:
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: IDENTITY_POOL_ID,
IdentityId: IdentityId,
Logins: {
'cognito-identity.amazonaws.com': Token,
},
});
const credentials = AWS.config.credentials;
const AWSAppSyncClient = require('aws-appsync').default;
const AUTH_TYPE = require('aws-appsync/lib/link/auth-link').AUTH_TYPE;
// Set up Apollo client
const client = new AWSAppSyncClient({
url: GRAPHQL_API_URL,
region: REGION,
auth: {
type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS,
credentials: credentials,
},
});
现在,当我进行查询
client.hydrated().then(function(client) {
//Now run a query
client
.query({ query: query })
.then(function logData(data) {
console.log('results of query: ', data);
})
.catch(console.error);
});
我得到错误:Network error: Response not successful: Received status code 401
。我是否缺少某些配置?
谢谢!
编辑:在联合身份中,我将Unauthenticated role
和Authenticated role
设置如下:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"appsync:GraphQL",
"mobileanalytics:PutEvents",
"cognito-sync:*"
],
"Resource": "*"
},
{
"Sid": "VisualEditor1",
"Effect": "Allow",
"Action": "appsync:GraphQL",
"Resource": "arn:aws:appsync:*:*:apis/*/types/*/fields/*"
},
{
"Sid": "VisualEditor2",
"Effect": "Allow",
"Action": "appsync:GraphQL",
"Resource": "arn:aws:appsync:*:*:apis/*"
}
]
}