@neo4j/graphql @auth指令CRUD权限配置异常问题求助
问题
使用@neo4j/graphql结合NestJS构建GraphQL API,定义了Todo模型,期望:
- 所有用户(包括未登录)可读取Todo数据
- 仅拥有ADMIN角色的登录用户可执行CREATE/DELETE/UPDATE操作
当前配置中,无token执行CUD操作会提示Unauthenticated(符合预期),但使用角色为['B']的token却能成功创建Todo,权限控制异常。相关代码如下:
// type-defs.ts export typeDefs = gql(` type Todo { id: ID! @id owner: String! title: String } extend type Todo @auth( rules: [ { operations: [READ], allowUnauthenticated: true } { operations: [CREATE, DELETE, UPDATE], allow: { roles: ["ADMIN"] } } ] ) `);
// gql.module.ts const neoSchema = new Neo4jGraphQL({ typeDefs, driver, plugins: { auth: new Neo4jGraphQLAuthJWKSPlugin({ jwksEndpoint: `https://cognito-idp.${process.env.COGNITO_REGION}.amazonaws.com/${process.env.COGNITO_USER_POOL_ID}`, }), }, }); @Module({ providers: [], imports: [ GraphQLModule.forRootAsync<ApolloDriverConfig>({ driver: ApolloDriver, useFactory: async () => { const schema = await neoSchema.getSchema(); await neoSchema.assertIndexesAndConstraints({ options: { create: true }, }); return { playground: true, schema, // 注释说明:将jwt.payload中的`cognito:groups`转换为`roles`传递给Neo4jGraphQLAuthJWKSPlugin context: authContextFunction, }; }, }), ], }) export class GqlModule {}
解决方案
1. 确认authContextFunction的角色映射逻辑
你的注释提到要把cognito:groups转为roles,但如果这个函数没有正确实现,会导致Neo4j GraphQL无法正确识别用户角色。确保函数准确提取并转换角色:
// 示例正确的authContextFunction实现 export const authContextFunction = ({ req }) => { const token = req.headers.authorization?.split('Bearer ')[1]; if (!token) return {}; // Neo4jGraphQLAuthJWKSPlugin会自动验证并解析token到context.auth // 需确保角色字段被正确映射为`roles` return { auth: { roles: req.auth.payload['cognito:groups'] || [], }, }; };
核心是保证context.auth.roles对应真实的用户角色列表,否则权限规则会失效。
2. 补全权限规则的严谨性
当前规则仅定义了允许ADMIN执行CUD,但未明确拒绝非ADMIN用户。可以添加明确的限制,确保只有符合条件的用户能操作:
extend type Todo @auth( rules: [ { operations: [READ], allowUnauthenticated: true } { operations: [CREATE, DELETE, UPDATE], allow: { roles: ["ADMIN"] }, // 明确拒绝未认证用户 allowUnauthenticated: false } ] )
或者添加更严格的拒绝规则:
extend type Todo @auth( rules: [ { operations: [READ], allowUnauthenticated: true } { operations: [CREATE, DELETE, UPDATE], allow: { roles: ["ADMIN"] }, deny: { roles_not: ["ADMIN"] } } ] )
3. 验证JWKS插件的token处理逻辑
确保Neo4jGraphQLAuthJWKSPlugin正确验证token的签名、过期时间等合法性。如果手动生成的token未经过Cognito签名,插件可能未正确拦截。可开启调试模式查看token解析日志:
new Neo4jGraphQLAuthJWKSPlugin({ jwksEndpoint: `https://cognito-idp.${process.env.COGNITO_REGION}.amazonaws.com/${process.env.COGNITO_USER_POOL_ID}`, debug: true, // 开启调试,查看token解析细节 })
4. 检查生成的Schema是否正确
确认neoSchema.getSchema()生成的Schema包含预期的权限规则,可打印Schema验证:
const schema = await neoSchema.getSchema(); console.log(schema.print()); // 输出完整Schema,检查Todo类型的@auth规则是否正确应用
内容的提问来源于stack exchange,提问作者akkonrad
相关产品推荐
相关产品推荐

