GraphQL 是一种用于 API 的查询语言,它允许客户端精确地请求需要的数据,避免了传统 REST API 中的过度获取数据的问题。然而,在 GraphQL 中,如果不进行权限控制,可能会导致敏感数据被未授权的用户访问。因此,本文将介绍如何在 GraphQL 中限制查询权限,以确保数据的安全性。
1. 使用认证和授权
在 GraphQL 中,认证和授权是限制查询权限的基本方法。认证是验证用户身份的过程,授权是确定用户是否有权进行某项操作。通过将认证和授权添加到 GraphQL API 中,可以限制未授权用户的查询和操作。
1.1 认证
在 GraphQL 中,认证通常通过在 HTTP 请求头中添加身份验证令牌来完成。例如,可以使用 JWT (JSON Web Token) 来进行身份验证,JWT 包含了用户的身份信息和过期时间,可以防止伪造身份验证令牌。
以下是一个使用 JWT 进行身份验证的示例:
// www.javascriptcn.com code example
type Query @authenticated {
me: User
}
type Mutation @authenticated {
createUser(input: CreateUserInput!): User
}
type User {
id: ID!
name: String!
email: String!
}
input CreateUserInput {
name: String!
email: String!
password: String!
}在上面的示例中,我们使用 @authenticated 指令来标记需要身份验证的查询和操作,这时可以在 GraphQL API 的上下文中检查用户是否已经进行了身份验证。
1.2 授权
在 GraphQL 中,授权通常通过在查询和操作中添加权限检查来完成。例如,可以检查当前用户是否具有执行操作的权限,如果没有权限,则返回错误。
以下是一个使用授权检查来限制查询权限的示例:
// www.javascriptcn.com code example
type Query {
me: User
users: [User] @hasRole(role: "admin")
}
type User {
id: ID!
name: String!
email: String!
}
directive @hasRole(role: String!) on FIELD_DEFINITION
extend type User @key(fields: "id") {
id: ID! @external
}在上面的示例中,我们使用 @hasRole 指令来标记需要进行权限检查的查询,这时可以在 GraphQL API 的上下文中检查当前用户是否具有执行查询的权限。
2. 使用 GraphQL Shield
GraphQL Shield 是一个用于 GraphQL 的轻量级权限控制库,它提供了一组简单但强大的 API,可以方便地实现各种权限控制方案。
以下是一个使用 GraphQL Shield 来限制查询权限的示例:
// www.javascriptcn.com code example
const { shield, rule, and, or, not } = require('graphql-shield');
const isAuthenticated = rule({ cache: 'contextual' })(
async (parent, args, ctx, info) => {
return ctx.user !== null;
},
);
const isAdmin = rule({ cache: 'contextual' })(
async (parent, args, ctx, info) => {
return ctx.user.role === 'admin';
},
);
const permissions = shield({
Query: {
me: isAuthenticated,
users: and(isAuthenticated, isAdmin),
},
});
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => {
const token = req.headers.authorization || '';
const user = verifyToken(token);
return { user };
},
plugins: [permissions],
});在上面的示例中,我们使用 rule 函数来定义权限检查规则,然后使用 shield 函数将权限检查规则应用到 GraphQL API 中。
3. 结语
在 GraphQL 中限制查询权限是确保数据安全的重要措施。本文介绍了使用认证和授权以及 GraphQL Shield 来限制查询权限的方法,希望对大家有所帮助。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d27baea941bf71344abf7b