|
| 1 | +/* |
| 2 | + * Copyright 2020-2021 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package org.springframework.boot.autoconfigure.graphql.security; |
| 18 | + |
| 19 | +import java.util.Collections; |
| 20 | +import java.util.function.Consumer; |
| 21 | + |
| 22 | +import graphql.schema.idl.TypeRuntimeWiring; |
| 23 | +import org.junit.jupiter.api.Test; |
| 24 | +import reactor.core.publisher.Mono; |
| 25 | + |
| 26 | +import org.springframework.boot.autoconfigure.AutoConfigurations; |
| 27 | +import org.springframework.boot.autoconfigure.graphql.Book; |
| 28 | +import org.springframework.boot.autoconfigure.graphql.GraphQlAutoConfiguration; |
| 29 | +import org.springframework.boot.autoconfigure.graphql.GraphQlTestDataFetchers; |
| 30 | +import org.springframework.boot.autoconfigure.graphql.reactive.GraphQlWebFluxAutoConfiguration; |
| 31 | +import org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration; |
| 32 | +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; |
| 33 | +import org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration; |
| 34 | +import org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration; |
| 35 | +import org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration; |
| 36 | +import org.springframework.boot.test.context.runner.ReactiveWebApplicationContextRunner; |
| 37 | +import org.springframework.context.annotation.Bean; |
| 38 | +import org.springframework.context.annotation.Configuration; |
| 39 | +import org.springframework.graphql.execution.ErrorType; |
| 40 | +import org.springframework.graphql.execution.RuntimeWiringConfigurer; |
| 41 | +import org.springframework.graphql.security.ReactiveSecurityDataFetcherExceptionResolver; |
| 42 | +import org.springframework.http.MediaType; |
| 43 | +import org.springframework.lang.Nullable; |
| 44 | +import org.springframework.security.access.prepost.PreAuthorize; |
| 45 | +import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity; |
| 46 | +import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; |
| 47 | +import org.springframework.security.config.web.server.ServerHttpSecurity; |
| 48 | +import org.springframework.security.core.userdetails.MapReactiveUserDetailsService; |
| 49 | +import org.springframework.security.core.userdetails.User; |
| 50 | +import org.springframework.security.core.userdetails.UserDetails; |
| 51 | +import org.springframework.security.web.server.SecurityWebFilterChain; |
| 52 | +import org.springframework.test.web.reactive.server.WebTestClient; |
| 53 | + |
| 54 | +import static org.assertj.core.api.Assertions.assertThat; |
| 55 | +import static org.springframework.security.config.Customizer.withDefaults; |
| 56 | + |
| 57 | +/** |
| 58 | + * Tests for {@link GraphQlWebFluxSecurityAutoConfiguration}. |
| 59 | + * |
| 60 | + * @author Brian Clozel |
| 61 | + */ |
| 62 | +class GraphQlWebFluxSecurityAutoConfigurationTests { |
| 63 | + |
| 64 | + private static final String BASE_URL = "https://spring.example.org/graphql"; |
| 65 | + |
| 66 | + private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() |
| 67 | + .withConfiguration(AutoConfigurations.of(HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, |
| 68 | + CodecsAutoConfiguration.class, JacksonAutoConfiguration.class, GraphQlAutoConfiguration.class, |
| 69 | + GraphQlWebFluxAutoConfiguration.class, GraphQlWebFluxSecurityAutoConfiguration.class, |
| 70 | + ReactiveSecurityAutoConfiguration.class)) |
| 71 | + .withUserConfiguration(DataFetchersConfiguration.class, SecurityConfig.class) |
| 72 | + .withPropertyValues("spring.main.web-application-type=reactive"); |
| 73 | + |
| 74 | + @Test |
| 75 | + void contributesExceptionResolver() { |
| 76 | + this.contextRunner.run( |
| 77 | + (context) -> assertThat(context).hasSingleBean(ReactiveSecurityDataFetcherExceptionResolver.class)); |
| 78 | + } |
| 79 | + |
| 80 | + @Test |
| 81 | + void anonymousUserShouldBeUnauthorized() { |
| 82 | + testWithWebClient((client) -> { |
| 83 | + String query = "{ bookById(id: \\\"book-1\\\"){ id name pageCount author }}"; |
| 84 | + client.post().uri("").bodyValue("{ \"query\": \"" + query + "\"}").exchange().expectStatus().isOk() |
| 85 | + .expectBody().jsonPath("data.bookById.name").doesNotExist() |
| 86 | + .jsonPath("errors[0].extensions.classification").isEqualTo(ErrorType.UNAUTHORIZED.toString()); |
| 87 | + }); |
| 88 | + } |
| 89 | + |
| 90 | + @Test |
| 91 | + void authenticatedUserShouldGetData() { |
| 92 | + testWithWebClient((client) -> { |
| 93 | + String query = "{ bookById(id: \\\"book-1\\\"){ id name pageCount author }}"; |
| 94 | + client.post().uri("").headers((headers) -> headers.setBasicAuth("rob", "rob")) |
| 95 | + .bodyValue("{ \"query\": \"" + query + "\"}").exchange().expectStatus().isOk().expectBody() |
| 96 | + .jsonPath("data.bookById.name").isEqualTo("GraphQL for beginners") |
| 97 | + .jsonPath("errors[0].extensions.classification").doesNotExist(); |
| 98 | + }); |
| 99 | + } |
| 100 | + |
| 101 | + private void testWithWebClient(Consumer<WebTestClient> consumer) { |
| 102 | + this.contextRunner.run((context) -> { |
| 103 | + WebTestClient client = WebTestClient.bindToApplicationContext(context).configureClient() |
| 104 | + .defaultHeaders((headers) -> { |
| 105 | + headers.setContentType(MediaType.APPLICATION_JSON); |
| 106 | + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); |
| 107 | + }).baseUrl(BASE_URL).build(); |
| 108 | + consumer.accept(client); |
| 109 | + }); |
| 110 | + } |
| 111 | + |
| 112 | + @Configuration(proxyBeanMethods = false) |
| 113 | + static class DataFetchersConfiguration { |
| 114 | + |
| 115 | + @Bean |
| 116 | + RuntimeWiringConfigurer bookDataFetcher(BookService bookService) { |
| 117 | + return (builder) -> builder.type(TypeRuntimeWiring.newTypeWiring("Query").dataFetcher("bookById", |
| 118 | + (env) -> bookService.getBookdById(env.getArgument("id")))); |
| 119 | + } |
| 120 | + |
| 121 | + @Bean |
| 122 | + BookService bookService() { |
| 123 | + return new BookService(); |
| 124 | + } |
| 125 | + |
| 126 | + } |
| 127 | + |
| 128 | + static class BookService { |
| 129 | + |
| 130 | + @PreAuthorize("hasRole('USER')") |
| 131 | + @Nullable |
| 132 | + Mono<Book> getBookdById(String id) { |
| 133 | + return Mono.justOrEmpty(GraphQlTestDataFetchers.getBookById(id)); |
| 134 | + } |
| 135 | + |
| 136 | + } |
| 137 | + |
| 138 | + @Configuration(proxyBeanMethods = false) |
| 139 | + @EnableWebFluxSecurity |
| 140 | + @EnableReactiveMethodSecurity |
| 141 | + static class SecurityConfig { |
| 142 | + |
| 143 | + @Bean |
| 144 | + SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) throws Exception { |
| 145 | + return http.csrf((spec) -> spec.disable()) |
| 146 | + // Demonstrate that method security works |
| 147 | + // Best practice to use both for defense in depth |
| 148 | + .authorizeExchange((requests) -> requests.anyExchange().permitAll()).httpBasic(withDefaults()) |
| 149 | + .build(); |
| 150 | + } |
| 151 | + |
| 152 | + @Bean |
| 153 | + @SuppressWarnings("deprecation") |
| 154 | + MapReactiveUserDetailsService userDetailsService() { |
| 155 | + User.UserBuilder userBuilder = User.withDefaultPasswordEncoder(); |
| 156 | + UserDetails rob = userBuilder.username("rob").password("rob").roles("USER").build(); |
| 157 | + UserDetails admin = userBuilder.username("admin").password("admin").roles("USER", "ADMIN").build(); |
| 158 | + return new MapReactiveUserDetailsService(rob, admin); |
| 159 | + } |
| 160 | + |
| 161 | + } |
| 162 | + |
| 163 | +} |
0 commit comments