首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Cognito用户池调用来自Lambda的APPSYNC突变- UnauthorizedException

使用Cognito用户池调用来自Lambda的APPSYNC突变- UnauthorizedException
EN

Stack Overflow用户
提问于 2018-12-13 17:45:29
回答 2查看 1.6K关注 0票数 1

我正在尝试调用Lambda的一个变异,它是由一个定时器定期触发的。这就是我正在做的事情

代码语言:javascript
复制
const params = {
    AccountId: "XXXXXXX",
    RoleArn: "arn:aws:iam::XXXX:role/appsync_lamda_role",     // tried removing this too
    IdentityPoolId: "ap-southeast-1:xxxx-xxxx-xxx-xxxx-xxx",
    LoginId: "demo_access" // tried with and without this
};
AWS.config.update({
    region: "ap-southeast-1",
    credentials: new AWS.CognitoIdentityCredentials(params)
});

现在,我打电话给

代码语言:javascript
复制
 AWS.config.credentials.get(err => {

    const signer = new AWS.Signers.V4(httpRequest, "appsync", true);
    signer.addAuthorization(AWS.config.credentials, AWS.util.date.getDate());


 const options = {
        method: httpRequest.method,
        body: httpRequest.body,
        headers: httpRequest.headers
    };

    fetch(uri.href, options)
        .then(res => res.json())
        .then(json => {
            console.log(`JSON Response = ${JSON.stringify(json, null, 2)}`);
            callback(null, event);
        })
        .catch(err => {
            console.error(`FETCH ERROR: ${JSON.stringify(err, null, 2)}`);
            callback(err);
        });
});

当我这样做时,我从APPSYNC得到一个错误,如"errors":[{ "errorType":"UnauthorizedException","message":"Unable to parse JWT token。“}我已经赋予了角色访问权限来调用GraphQL并编辑了信任关系

代码语言:javascript
复制
 {
     "Effect": "Allow",
      "Principal": {
        "Federated": "cognito-identity.amazonaws.com"
       },
        "Action": "sts:AssumeRoleWithWebIdentity"
    }

我在这里错过了什么?请帮帮忙。

当我查看生成的头部时,我没有看到JWT令牌,但我看到了会话令牌,如下所示

代码语言:javascript
复制
 'User-Agent': 'aws-sdk-nodejs/2.275.1 linux/v8.10.0 exec-env/AWS_Lambda_nodejs8.10',
host: 'xxxxx.appsync-api.ap-southeast-1.amazonaws.com',
'Content-Type': 'application/json',
'X-Amz-Date': '20181213T080156Z',
'x-amz-security-token': 'xxxxxx//////////xxxxxEOix8u062xxxxxynf4Q08FxxxLZxV+xx/xxx/xxx/xxxxx=',
Authorization: 'AWS4-HMAC-SHA256 Credential=xxxxxxxxx/20181213/ap-southeast-1/appsync/aws4_request, SignedHeaders=host;x-amz-date;x-amz-security-token, Signature=xxxxxxxxxxxxxxxxxxxxxxx' }

提前感谢

EN

回答 2

Stack Overflow用户

发布于 2018-12-14 05:12:13

亚马逊网络服务AppSync支持通过IAM和Cognito用户池进行授权。它们可能会令人困惑,根据我的经验,AWS文档和框架在这种混乱中无能为力。

IAM身份验证是所有主要AWS端点都使用的身份验证。您可以使用正确的IAM身份验证和权限创建一个DynamoDB表。IAM请求(通常由SDK或boto发出)是通过使用您的密钥对特定的主机、路径、参数和头部进行签名,将其转换为签名。您的Authorization头以AWS4-HMAC-SHA256开头,所以看起来您使用的是带有v4签名的IAM授权。

Cognito用户池身份验证使用JWT令牌进行授权。在使用Cognito服务器进行身份验证之后,您将获得一个访问令牌和一个身份令牌,它们可用于调用AWS Appsync等资源。如果您将Cognito User Pool连接到Cognito Identity Pool,那么使用这些访问令牌,就可以检索IAM令牌。如果这样做,则可以使用这些令牌对IAM身份验证请求进行签名。

看起来您使用Cognito User Pool身份验证配置了您的API,但是您正在使用AppSync身份验证调用它。您可以使用JWT身份验证开始调用它,也可以将您的AWS IAM应用编程接口切换为使用AppSync身份验证。您选择的身份验证方法会影响您如何实施细粒度的访问控制(在IAM策略中与在您的GraphQL模式中)。在docs上阅读更多关于它的信息。

票数 4
EN

Stack Overflow用户

发布于 2019-01-31 17:31:02

您可以尝试这样做:

代码语言:javascript
复制
import 'babel-polyfill';
import URL from 'url';
import fetch from 'node-fetch';
import { CognitoIdentityServiceProvider } from 'aws-sdk';

const cognitoIdentityServiceProvider = new CognitoIdentityServiceProvider({ apiVersion: '2016-04-18' });
const initiateAuth = async ({ clientId, username, password }) => cognitoIdentityServiceProvider.initiateAuth({
    AuthFlow: 'USER_PASSWORD_AUTH',
    ClientId: clientId,
    AuthParameters: {
      USERNAME: username,
      PASSWORD: password,
    },
  })
  .promise();

export const handler = async (event, context, callback) => {
  const clientId = 'YOUR_COGNITO_CLIENT_ID';
  const endPoint = 'YOUR_GRAPHQL_END_POINT_URL';
  const username = 'COGNITO_USERNAME';
  const password = 'COGNITO_PASSWORD';
  const { AuthenticationResult } = await initiateAuth({
    clientId,
    username,
    password,
  });
  const accessToken = AuthenticationResult && AuthenticationResult.AccessToken;
  const postBody = {
    query: `mutation AddUser($userId: ID!, $userDetails: UserInput!) {
        addUser(userId: $userId, userDetails: $userDetails) {
            userId
            name
        }`,
    variables: {
        userId: 'userId',
        userDetails: { name: 'name' },
    },
  };

  const uri = await URL.parse(endPoint);

  const options = {
    method: 'POST',
    body: JSON.stringify(postBody),
    headers: {
      host: uri.host,
      'Content-Type': 'application/json',
      Authorization: accessToken,
    },
  };
  const response = await fetch(uri.href, options);
  const { data } = await response.json();

  const result = data && data.addUser;
  callback(null, result);
};

确保您的Cognito User Pool具有USER_PASSWORD_AUTH身份验证流。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53758959

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档