首页 > 解决方案 > 在 graphql-java-tools 中禁用 GraphQL Introspection

问题描述

我试图GraphQL在我的项目中禁用 Introspection,并且对我正在使用的特定框架没有太多运气。一些文章说它可以在CcodeRegistry模块中完成,但这是一个只读的反编译源。有没有人通过 GraphQL-java-kickstart框架实现了这一点?

以下是我的 pom 文件中的依赖项:

        <dependency>
            <groupId>com.graphql-java</groupId>
            <artifactId>graphql-java</artifactId>
            <version>${graphql.java.version}</version>
        </dependency>
        <dependency>
            <groupId>com.graphql-java-kickstart</groupId>
            <artifactId>graphql-java-tools</artifactId>
            <version>${graphql.java.tools.version}</version>
        </dependency>
        <dependency>
            <groupId>com.graphql-java</groupId>
            <artifactId>graphql-java-extended-validation</artifactId>
            <version>0.0.3</version>
        </dependency>

标签: graphqlgraphql-javagraphql-schemagraphql-java-tools

解决方案


Graphql-java

使用 graphql-java,您可以GraphQLSchema使用GraphQLSchema.Builder. 您需要在构建之前为自省字段设置构建器可见性以禁用自省查询。

GraphQLSchema.Builder builder = GraphQLSchema.newSchema()
                                     .query(query)
                                     .mutation(mutation)
                                     .subscription(subscription)
                                     .additionalTypes(dictionary);

builder.fieldVisibility(NoIntrospectionGraphqlFieldVisibility.NO_INTROSPECTION_FIELD_VISIBILITY);

GraphQLSchema = builder.build();

您可以使用graphql-java-tools 实现作为参考。

Graphql-java-tools

使用 graphql-java-tools,您可以SchemaParser 使用SchemaParserBuilder. SchemaParserBuilder 需要一个 SchemaParserOptions 对象。在构建 SchemaParserOptions 时,您可以启用或禁用自省查询。这是一个非常简化的实现。

SchemaParserBuilder builder = new SchemaParserBuilder();
final SchemaParserOptions.Builder optionsBuilder = newOptions();
optionsBuilder.introspectionEnabled(introspectionEnabled);
return builder.options(optionsBuilder.build()).build();

您可以使用graphql-spring-boot 实现作为参考。

Graphql-spring-boot

如果您使用的是 graphql-spring-boot,根据 graphql-java-tools READMEgraphql.tools.introspection-enabled ,您可以通过在 application.properties 或 application.yml 文件中将属性设置为 false 来禁用自省查询。

graphql:
    tools:
        schema-location-pattern: "**/*.graphqls"
        # Enable or disable the introspection query. Disabling it puts your server in contravention of the GraphQL
        # specification and expectations of most clients, so use this option with caution
        introspection-enabled: false  

Graphql-spqr

使用 Graphql-spqr,想法与 graphql-java 中的相同:设置构建器字段可见性。有关如何实现它,请参阅我对这个问题的回答。


推荐阅读