Christof Aenderl
Christof Aenderl

Reputation: 4512

Use introspection query without authentication in graphql-spring-boot-starter

Using the graphql-spring-boot-starter library https://github.com/graphql-java-kickstart/graphql-spring-boot, is it possible to secure all requests but allow only the graphql introspection query with authentication?

The project has enabled Spring security to use OAuth2 so every request is secured.

Thanks for any hint or help.

Upvotes: 6

Views: 1397

Answers (1)

pratibha negi
pratibha negi

Reputation: 23

You can define a property in application.yml for the graphql operations that you'd like to perform without authorization. As an example, in application.yml -> authorization: excludedoperation: IntrospectionQuery

In WebSecurityConfig.java, you can bind your excludedOperation variable as below, @Value("${authorization.excludedoperation}") private String excludedOperations;

and define excludedOperation as a field in the implementation of GraphQLServletExecutor, GraphQLServletExecutorImpl. In WebSecurityConfig.java, from @Bean method that returns GraphQLServletExecutor (replacement of SpqrMvcAutoConfiguration.graphQLExecutor) newGraphQLExecutor, return GraphQLServletExecutorImpl with excludedOperation as one of the constructor parameter.

In the GraphQLServletExecutorImpl, make sure in execute function that you do the authorization only if OperationName in GraphQL request does not contain excluded operation (in your case IntrospectionQuery) GraphQLServletExecutorImpl,

public Map<String, Object> execute(GraphQL graphQL, GraphQLRequest graphQLRequest, NativeWebRequest nativeRequest) {

    ExecutionInput input = buildInput(graphQLRequest, nativeRequest, contextFactory, dataLoaderRegistryFactory);

    if (!excludedOperations.contains(graphQLRequest.getOperationName())) {
        
        // check the access_token
        HttpServletRequest request = nativeRequest.getNativeRequest(HttpServletRequest.class);
            bearerTokenAuthorizer.authorize(EMPTY_AUTH_ANNOTATION, request);
            //do your thing

    }

    return graphQL.execute(input).toSpecification();
}

Upvotes: 1

Related Questions