首页 > 解决方案 > 使用 Cognito 对 AWS-Amplify 中的 Lambda 函数进行查询和更改 GraphQL 进行身份验证

问题描述

我通过命令创建了一个 GraphQL apiamplify api add并添加了下面的模式。我正在使用 cognito 进行身份验证。

type User @model
  @auth(rules: [{ allow: owner }]) {
  id: ID!

  videos: [Video!] @connection(keyName: "videosByUser", fields: ["id"])
  adverts: [Advert] @connection(keyName:"advertsByUser", fields: ["id"])
}

type Video @model
  @key(name: "videosByUser", fields: ["userId"])
  @auth(rules: [{ allow: owner, operations: [create, update, delete] }]) {

  id: ID!
  title: String!
  description: String!

  size: Float!
  length: Float!
  hashMarks: [Float!]!

  userId: ID!
  # bidrectional connection, if needed
  # user: User! @connection(fields: ["userId"])

  adverts: [VideoAdverts!] @connection(keyName: "advertsByVideo", fields: ["id"])
  streamingLink: AWSURL
}

type VideoAdverts @model(queries: null)
  @key(name: "advertsByVideo", fields: ["videoId", "advertId"])
  @key(name: "videosByAdvert", fields: ["advertId", "videoId"]) {

  id: ID!
  videoId: ID!
  advertId: ID!

  video: Video! @connection(fields: ["videoId"])
  advert: Advert! @connection(fields: ["advertId"])
}

type Advert @model
  @key(name: "advertsByUser", fields: ["userId"])
  @auth(rules: [{ allow: owner, operations: [create, update, delete] }]) {

  id: ID!
  title: String!
  description: String!

  size: Float!
  length: Float!

  creatorId: ID!
  # bidrectional connection, if needed
  # creator: Creator! @connection(fields: ["creatorId"])

  videos: [VideoAdverts!] @connection(keyName: "videosByAdvert", fields: ["id"])
  blacklist: [AdvertBlacklist!] @connection(keyName: "blacklistByAdvert", fields: ["id"])

  startDate: AWSDateTime
  endDate: AWSDateTime
}

这是我的第一个放大项目,我无法弄清楚如何实现以下用例:

  1. 使用 lambda 函数查询数据并返回给客户端。
  2. 使用 cron 触发的 lambda 函数进行 API 调用并使用突变来更新某些字段。

到目前为止,我在谷歌搜索中发现的所有内容都涉及使用 lambda 与通过amplify storage add命令添加的数据进行交互。

我在 Stackoverflow 上找到的其他一些示例不使用 cognito 进行身份验证。

看起来我将能够使用 cloudwatch 来触发 lambda,所以我现在的主要问题是如何使用 cognito 进行身份验证,从 lambda 中实际查询和改变 GraphQL api。任何帮助都会非常有帮助,谢谢:)

标签: aws-lambdaaws-amplifyaws-amplify-cli

解决方案


对 Lambda 函数进行身份验证以与 AppSync API 交互的关键是配置多种身份验证方法。您正在为您的前端应用程序用户使用 Cognito,但是,您不希望将其用于您的 Lambda 函数身份验证。AppSync 支持 API 的多种身份验证机制。在您的情况下,您需要添加 IAM 作为第二个身份验证机制。

您可以从 Amplify CLI 执行此操作:

$ amplify update api

Scanning for plugins...
Plugin scan successful

? Please select from one of the below mentioned services: GraphQL

? Choose the default authorization type for the API Amazon Cognito User Pool
Use a Cognito user pool configured as a part of this project.

? Do you want to configure advanced settings for the GraphQL API Yes, I want 
to make some additional changes.

? Configure additional auth types? Yes

? Choose the additional authorization types you want to configure for the API IAM

推荐阅读