AWS Amplify是一款非常流行的JavaScript库,用于加速构建云应用程序。它允许开发人员使用GraphQL API轻松管理应用程序的数据。然而,在处理通过GraphQL API获取或更改的敏感数据时,安全性是一个非常重要的问题。AWS Amplify提供了一种简单的解决方案,即字段级别认证,以确保只有授权用户可以访问需要身份验证的字段。
以下是AWS Amplify中使用字段级别认证的示例代码:
type Post
{
id: ID!
title: String!
content: String!
author: Author @auth(rules: [{ allow: groups, groups: ["Admins", "Editors"] }])
createdAt: String!
}
type Author
{
id: ID!
name: String!
email: String! @auth(rules: [{ allow: owner }])
posts: [Post]
}
type Query
{
posts: [Post] @auth(rules: [ { allow: groups, groups: ["Admins", "Editors", "Readers"] } ])
post(id: ID!): Post @auth(rules: [ { allow: groups, groups: ["Admins", "Editors", "Readers"] } ])
}
type Mutation
{
createPost(title: String!, content: String!): Post @auth(rules: [{ allow: groups, groups: ["Admins", "Editors"] }])
updatePost(id: ID!, title: String, content: String): Post @auth(rules: [{ allow: groups, groups: ["Admins", "Editors"] }])
deletePost(id: ID!): Post @auth(rules: [{ allow: groups, groups: ["Admins"] }])
}
如你所见,@auth指令用于标注需要进行字段级别身份验证的字段。在上面的示例中,我们'author”的字段标记为只允许属于“Admins”或“Editors”组的用户访问;我们还'email”的字段标记为只