diff --git a/samples/tutorials/reactive-resource-server/src/main/java/com/c4soft/springaddons/tutorials/GreetingController.java b/samples/tutorials/reactive-resource-server/src/main/java/com/c4soft/springaddons/tutorials/GreetingController.java index 9d6ff7bae..3471dfef4 100644 --- a/samples/tutorials/reactive-resource-server/src/main/java/com/c4soft/springaddons/tutorials/GreetingController.java +++ b/samples/tutorials/reactive-resource-server/src/main/java/com/c4soft/springaddons/tutorials/GreetingController.java @@ -4,7 +4,6 @@ import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; - import reactor.core.publisher.Mono; @RestController diff --git a/samples/tutorials/reactive-resource-server/src/main/java/com/c4soft/springaddons/tutorials/WebSecurityConfig.java b/samples/tutorials/reactive-resource-server/src/main/java/com/c4soft/springaddons/tutorials/WebSecurityConfig.java index f078d0e74..fded57731 100644 --- a/samples/tutorials/reactive-resource-server/src/main/java/com/c4soft/springaddons/tutorials/WebSecurityConfig.java +++ b/samples/tutorials/reactive-resource-server/src/main/java/com/c4soft/springaddons/tutorials/WebSecurityConfig.java @@ -1,7 +1,6 @@ package com.c4soft.springaddons.tutorials; import static org.springframework.security.config.Customizer.withDefaults; - import java.net.URL; import java.nio.charset.Charset; import java.util.Arrays; @@ -10,7 +9,6 @@ import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; - import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -44,11 +42,9 @@ import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; import org.springframework.web.server.ServerWebExchange; - import com.c4soft.springaddons.tutorials.WebSecurityConfig.SpringAddonsProperties.IssuerProperties; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.PathNotFoundException; - import lombok.Data; import lombok.RequiredArgsConstructor; import reactor.core.publisher.Mono; diff --git a/samples/tutorials/reactive-resource-server/src/test/java/com/c4soft/springaddons/tutorials/GreetingControllerTest.java b/samples/tutorials/reactive-resource-server/src/test/java/com/c4soft/springaddons/tutorials/GreetingControllerTest.java index 39a3dc5ec..58620a475 100644 --- a/samples/tutorials/reactive-resource-server/src/test/java/com/c4soft/springaddons/tutorials/GreetingControllerTest.java +++ b/samples/tutorials/reactive-resource-server/src/test/java/com/c4soft/springaddons/tutorials/GreetingControllerTest.java @@ -2,7 +2,6 @@ import java.util.Optional; import java.util.stream.Stream; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; @@ -11,7 +10,6 @@ import org.junit.jupiter.params.provider.MethodSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.core.convert.converter.Converter; import org.springframework.security.authentication.AbstractAuthenticationToken; @@ -24,15 +22,14 @@ import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers; import org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.JwtMutator; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.server.ServerWebExchange; - import com.c4_soft.springaddons.security.oauth2.test.annotations.WithJwt; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockAuthentication; import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.AuthenticationSource; import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.ParameterizedAuthentication; import com.c4soft.springaddons.tutorials.GreetingController.MessageDto; - import reactor.core.publisher.Mono; @WebFluxTest(controllers = GreetingController.class, properties = "server.ssl.enabled=false") @@ -42,7 +39,7 @@ class GreetingControllerTest { static final AnonymousAuthenticationToken ANONYMOUS = new AnonymousAuthenticationToken("anonymous", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); - @MockBean + @MockitoBean ReactiveAuthenticationManagerResolver authenticationManagerResolver; @Autowired diff --git a/samples/tutorials/reactive-resource-server/src/test/java/com/c4soft/springaddons/tutorials/ReactiveResourceServerApplicationTests.java b/samples/tutorials/reactive-resource-server/src/test/java/com/c4soft/springaddons/tutorials/ReactiveResourceServerApplicationTests.java index 2d407892a..716a63d31 100644 --- a/samples/tutorials/reactive-resource-server/src/test/java/com/c4soft/springaddons/tutorials/ReactiveResourceServerApplicationTests.java +++ b/samples/tutorials/reactive-resource-server/src/test/java/com/c4soft/springaddons/tutorials/ReactiveResourceServerApplicationTests.java @@ -2,7 +2,6 @@ import java.util.Optional; import java.util.stream.Stream; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; @@ -13,7 +12,6 @@ import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.core.convert.converter.Converter; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.authentication.AnonymousAuthenticationToken; @@ -25,15 +23,14 @@ import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers; import org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.JwtMutator; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.server.ServerWebExchange; - import com.c4_soft.springaddons.security.oauth2.test.annotations.WithJwt; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockAuthentication; import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.AuthenticationSource; import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.ParameterizedAuthentication; import com.c4soft.springaddons.tutorials.GreetingController.MessageDto; - import reactor.core.publisher.Mono; @SpringBootTest(webEnvironment = WebEnvironment.MOCK) @@ -43,7 +40,7 @@ class ReactiveResourceServerApplicationTests { static final AnonymousAuthenticationToken ANONYMOUS = new AnonymousAuthenticationToken("anonymous", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); - @MockBean + @MockitoBean ReactiveAuthenticationManagerResolver authenticationManagerResolver; @Autowired diff --git a/samples/tutorials/servlet-resource-server/src/main/java/com/c4soft/springaddons/tutorials/WebSecurityConfig.java b/samples/tutorials/servlet-resource-server/src/main/java/com/c4soft/springaddons/tutorials/WebSecurityConfig.java index 72bab2659..b1b972bac 100644 --- a/samples/tutorials/servlet-resource-server/src/main/java/com/c4soft/springaddons/tutorials/WebSecurityConfig.java +++ b/samples/tutorials/servlet-resource-server/src/main/java/com/c4soft/springaddons/tutorials/WebSecurityConfig.java @@ -7,7 +7,6 @@ import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; - import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -38,10 +37,8 @@ import org.springframework.stereotype.Component; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; - import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.PathNotFoundException; - import jakarta.servlet.http.HttpServletRequest; import lombok.Data; import lombok.RequiredArgsConstructor; diff --git a/samples/tutorials/servlet-resource-server/src/test/java/com/c4soft/springaddons/tutorials/GreetingControllerTest.java b/samples/tutorials/servlet-resource-server/src/test/java/com/c4soft/springaddons/tutorials/GreetingControllerTest.java index b1ad7ca78..715ac44b2 100644 --- a/samples/tutorials/servlet-resource-server/src/test/java/com/c4soft/springaddons/tutorials/GreetingControllerTest.java +++ b/samples/tutorials/servlet-resource-server/src/test/java/com/c4soft/springaddons/tutorials/GreetingControllerTest.java @@ -3,32 +3,29 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.security.authentication.AuthenticationManagerResolver; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; - import com.c4_soft.springaddons.security.oauth2.test.annotations.WithJwt; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockAuthentication; import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.AuthenticationSource; import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.ParameterizedAuthentication; - import jakarta.servlet.http.HttpServletRequest; @WebMvcTest(controllers = GreetingController.class, properties = { "server.ssl.enabled=false" }) @Import({ WebSecurityConfig.class }) class GreetingControllerTest { - @MockBean + @MockitoBean AuthenticationManagerResolver authenticationManagerResolver; @Autowired diff --git a/samples/tutorials/servlet-resource-server/src/test/java/com/c4soft/springaddons/tutorials/ServletResourceServerApplicationTests.java b/samples/tutorials/servlet-resource-server/src/test/java/com/c4soft/springaddons/tutorials/ServletResourceServerApplicationTests.java index fb41225e3..2e2e16304 100644 --- a/samples/tutorials/servlet-resource-server/src/test/java/com/c4soft/springaddons/tutorials/ServletResourceServerApplicationTests.java +++ b/samples/tutorials/servlet-resource-server/src/test/java/com/c4soft/springaddons/tutorials/ServletResourceServerApplicationTests.java @@ -3,25 +3,23 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.authentication.AuthenticationManagerResolver; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; - import jakarta.servlet.http.HttpServletRequest; @SpringBootTest(webEnvironment = WebEnvironment.MOCK, properties = { "server.ssl.enabled=false" }) @AutoConfigureMockMvc class ServletResourceServerApplicationTests { - @MockBean + @MockitoBean AuthenticationManagerResolver authenticationManagerResolver; @Autowired diff --git a/samples/webflux-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerAnnotatedTest.java b/samples/webflux-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerAnnotatedTest.java index 2af4545d6..4db08827b 100644 --- a/samples/webflux-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerAnnotatedTest.java +++ b/samples/webflux-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerAnnotatedTest.java @@ -1,32 +1,31 @@ /* * Copyright 2019 Jérôme Wacongne. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the - * License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package com.c4_soft.springaddons.samples.webflux_jwtauthenticationtoken; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication; - +import org.springframework.test.context.bean.override.mockito.MockitoBean; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockAuthentication; import com.c4_soft.springaddons.security.oauth2.test.webflux.AutoConfigureAddonsWebfluxResourceServerSecurity; import com.c4_soft.springaddons.security.oauth2.test.webflux.WebTestClientSupport; - import reactor.core.publisher.Mono; /** @@ -36,68 +35,78 @@ */ @WebFluxTest(GreetingController.class) // Use WebFluxTest or WebMvcTest -@AutoConfigureAddonsWebfluxResourceServerSecurity // If your web-security depends on it, setup spring-addons security -@Import({ SecurityConfig.class }) // Import your web-security configuration +@AutoConfigureAddonsWebfluxResourceServerSecurity // If your web-security depends on it, setup + // spring-addons security +@Import({SecurityConfig.class}) // Import your web-security configuration class GreetingControllerAnnotatedTest { - // Mock controller injected dependencies - @MockBean - private MessageService messageService; - - @Autowired - WebTestClientSupport api; - - @BeforeEach - public void setUp() { - when(messageService.greet(any())).thenAnswer(invocation -> { - final BearerTokenAuthentication auth = invocation.getArgument(0, BearerTokenAuthentication.class); - return Mono.just(String.format("Hello %s! You are granted with %s.", auth.getName(), auth.getAuthorities())); - }); - when(messageService.getSecret()).thenReturn(Mono.just("Secret message")); - } - - @Test - void givenRequestIsAnonymous_whenGetGreet_thenUnauthorized() throws Exception { - api.get("https://localhost/greet").expectStatus().isUnauthorized(); - } - - @Test - @WithMockAuthentication(authType = BearerTokenAuthentication.class, principalType = OAuth2AccessToken.class, authorities = "ROLE_AUTHORIZED_PERSONNEL") - void givenUserIsAuthenticated_whenGetGreet_thenOk() throws Exception { - api.get("https://localhost/greet").expectBody(String.class).isEqualTo("Hello user! You are granted with [ROLE_AUTHORIZED_PERSONNEL]."); - } - - @Test - @WithMockAuthentication( - authType = BearerTokenAuthentication.class, - principalType = OAuth2AccessToken.class, - name = "Ch4mpy", - authorities = "ROLE_AUTHORIZED_PERSONNEL") - void givenUserIsCh4mpy_whenGetGreet_thenOk() throws Exception { - api.get("https://localhost/greet").expectBody(String.class).isEqualTo("Hello Ch4mpy! You are granted with [ROLE_AUTHORIZED_PERSONNEL]."); - } - - @Test - @WithMockAuthentication(authType = BearerTokenAuthentication.class, principalType = OAuth2AccessToken.class) - void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() throws Exception { - api.get("https://localhost/secured-route").expectStatus().isForbidden(); - } - - @Test - @WithMockAuthentication(authType = BearerTokenAuthentication.class, principalType = OAuth2AccessToken.class, authorities = "ROLE_AUTHORIZED_PERSONNEL") - void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception { - api.get("https://localhost/secured-route").expectStatus().isOk(); - } - - @Test - @WithMockAuthentication(authType = BearerTokenAuthentication.class, principalType = OAuth2AccessToken.class) - void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() throws Exception { - api.get("https://localhost/secured-method").expectStatus().isForbidden(); - } - - @Test - @WithMockAuthentication(authType = BearerTokenAuthentication.class, principalType = OAuth2AccessToken.class, authorities = "ROLE_AUTHORIZED_PERSONNEL") - void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception { - api.get("https://localhost/secured-method").expectStatus().isOk(); - } + // Mock controller injected dependencies + @MockitoBean + private MessageService messageService; + + @Autowired + WebTestClientSupport api; + + @BeforeEach + public void setUp() { + when(messageService.greet(any())).thenAnswer(invocation -> { + final BearerTokenAuthentication auth = + invocation.getArgument(0, BearerTokenAuthentication.class); + return Mono.just(String.format("Hello %s! You are granted with %s.", auth.getName(), + auth.getAuthorities())); + }); + when(messageService.getSecret()).thenReturn(Mono.just("Secret message")); + } + + @Test + void givenRequestIsAnonymous_whenGetGreet_thenUnauthorized() throws Exception { + api.get("https://localhost/greet").expectStatus().isUnauthorized(); + } + + @Test + @WithMockAuthentication(authType = BearerTokenAuthentication.class, + principalType = OAuth2AccessToken.class, authorities = "ROLE_AUTHORIZED_PERSONNEL") + void givenUserIsAuthenticated_whenGetGreet_thenOk() throws Exception { + api.get("https://localhost/greet").expectBody(String.class) + .isEqualTo("Hello user! You are granted with [ROLE_AUTHORIZED_PERSONNEL]."); + } + + @Test + @WithMockAuthentication(authType = BearerTokenAuthentication.class, + principalType = OAuth2AccessToken.class, name = "Ch4mpy", + authorities = "ROLE_AUTHORIZED_PERSONNEL") + void givenUserIsCh4mpy_whenGetGreet_thenOk() throws Exception { + api.get("https://localhost/greet").expectBody(String.class) + .isEqualTo("Hello Ch4mpy! You are granted with [ROLE_AUTHORIZED_PERSONNEL]."); + } + + @Test + @WithMockAuthentication(authType = BearerTokenAuthentication.class, + principalType = OAuth2AccessToken.class) + void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() + throws Exception { + api.get("https://localhost/secured-route").expectStatus().isForbidden(); + } + + @Test + @WithMockAuthentication(authType = BearerTokenAuthentication.class, + principalType = OAuth2AccessToken.class, authorities = "ROLE_AUTHORIZED_PERSONNEL") + void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception { + api.get("https://localhost/secured-route").expectStatus().isOk(); + } + + @Test + @WithMockAuthentication(authType = BearerTokenAuthentication.class, + principalType = OAuth2AccessToken.class) + void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() + throws Exception { + api.get("https://localhost/secured-method").expectStatus().isForbidden(); + } + + @Test + @WithMockAuthentication(authType = BearerTokenAuthentication.class, + principalType = OAuth2AccessToken.class, authorities = "ROLE_AUTHORIZED_PERSONNEL") + void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception { + api.get("https://localhost/secured-method").expectStatus().isOk(); + } } diff --git a/samples/webflux-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerFluentApiTest.java b/samples/webflux-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerFluentApiTest.java index 2a6354412..e7ee09016 100644 --- a/samples/webflux-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerFluentApiTest.java +++ b/samples/webflux-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerFluentApiTest.java @@ -1,25 +1,25 @@ /* * Copyright 2019 Jérôme Wacongne. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the - * License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package com.c4_soft.springaddons.samples.webflux_jwtauthenticationtoken; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.mockOpaqueToken; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.authority.AuthorityUtils; @@ -28,10 +28,9 @@ import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication; import org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers; import org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.OpaqueTokenMutator; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.reactive.server.WebTestClient; - import com.c4_soft.springaddons.security.oauth2.test.webflux.AutoConfigureAddonsWebfluxResourceServerSecurity; - import reactor.core.publisher.Mono; /** @@ -39,60 +38,71 @@ */ @WebFluxTest(GreetingController.class) @AutoConfigureAddonsWebfluxResourceServerSecurity -@Import({ SecurityConfig.class }) +@Import({SecurityConfig.class}) public class GreetingControllerFluentApiTest { - static final AnonymousAuthenticationToken ANONYMOUS = - new AnonymousAuthenticationToken("anonymous", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); + static final AnonymousAuthenticationToken ANONYMOUS = new AnonymousAuthenticationToken( + "anonymous", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); - @MockBean - private MessageService messageService; + @MockitoBean + private MessageService messageService; - @Autowired - WebTestClient api; + @Autowired + WebTestClient api; - @BeforeEach - public void setUp() { - when(messageService.greet(any())).thenAnswer(invocation -> { - final BearerTokenAuthentication auth = invocation.getArgument(0, BearerTokenAuthentication.class); - return Mono.just(String.format("Hello %s! You are granted with %s.", auth.getTokenAttributes().get(StandardClaimNames.PREFERRED_USERNAME), auth.getAuthorities())); - }); - when(messageService.getSecret()).thenReturn(Mono.just("Secret message")); - } + @BeforeEach + public void setUp() { + when(messageService.greet(any())).thenAnswer(invocation -> { + final BearerTokenAuthentication auth = + invocation.getArgument(0, BearerTokenAuthentication.class); + return Mono.just(String.format("Hello %s! You are granted with %s.", + auth.getTokenAttributes().get(StandardClaimNames.PREFERRED_USERNAME), + auth.getAuthorities())); + }); + when(messageService.getSecret()).thenReturn(Mono.just("Secret message")); + } - @Test - void givenRequestIsAnonymous_whenGetGreet_thenUnauthorized() throws Exception { - api.mutateWith(SecurityMockServerConfigurers.mockAuthentication(ANONYMOUS)).get().uri("https://localhost/greet").exchange().expectStatus() - .isUnauthorized(); - } + @Test + void givenRequestIsAnonymous_whenGetGreet_thenUnauthorized() throws Exception { + api.mutateWith(SecurityMockServerConfigurers.mockAuthentication(ANONYMOUS)).get() + .uri("https://localhost/greet").exchange().expectStatus().isUnauthorized(); + } - @Test - void givenUserIsCh4mpy_whenGetGreet_thenOk() throws Exception { - api.mutateWith(ch4mpy()).get().uri("https://localhost/greet").exchange().expectBody(String.class) - .isEqualTo("Hello Ch4mpy! You are granted with [ROLE_AUTHORIZED_PERSONNEL]."); - } + @Test + void givenUserIsCh4mpy_whenGetGreet_thenOk() throws Exception { + api.mutateWith(ch4mpy()).get().uri("https://localhost/greet").exchange() + .expectBody(String.class) + .isEqualTo("Hello Ch4mpy! You are granted with [ROLE_AUTHORIZED_PERSONNEL]."); + } - @Test - void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() throws Exception { - api.mutateWith(mockOpaqueToken()).get().uri("https://localhost/secured-route").exchange().expectStatus().isForbidden(); - } + @Test + void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() + throws Exception { + api.mutateWith(mockOpaqueToken()).get().uri("https://localhost/secured-route").exchange() + .expectStatus().isForbidden(); + } - @Test - void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() throws Exception { - api.mutateWith(mockOpaqueToken()).get().uri("https://localhost/secured-method").exchange().expectStatus().isForbidden(); - } + @Test + void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() + throws Exception { + api.mutateWith(mockOpaqueToken()).get().uri("https://localhost/secured-method").exchange() + .expectStatus().isForbidden(); + } - @Test - void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception { - api.mutateWith(ch4mpy()).get().uri("https://localhost/secured-route").exchange().expectStatus().isOk(); - } + @Test + void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception { + api.mutateWith(ch4mpy()).get().uri("https://localhost/secured-route").exchange().expectStatus() + .isOk(); + } - @Test - void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception { - api.mutateWith(ch4mpy()).get().uri("https://localhost/secured-method").exchange().expectStatus().isOk(); - } + @Test + void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception { + api.mutateWith(ch4mpy()).get().uri("https://localhost/secured-method").exchange().expectStatus() + .isOk(); + } - private OpaqueTokenMutator ch4mpy() { - return mockOpaqueToken().attributes(attributes -> attributes.put(StandardClaimNames.PREFERRED_USERNAME, "Ch4mpy")) - .authorities(new SimpleGrantedAuthority("ROLE_AUTHORIZED_PERSONNEL")); - } + private OpaqueTokenMutator ch4mpy() { + return mockOpaqueToken() + .attributes(attributes -> attributes.put(StandardClaimNames.PREFERRED_USERNAME, "Ch4mpy")) + .authorities(new SimpleGrantedAuthority("ROLE_AUTHORIZED_PERSONNEL")); + } } diff --git a/samples/webflux-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/MessageServiceTests.java b/samples/webflux-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/MessageServiceTests.java index 8263b8f6a..2ab608f1c 100644 --- a/samples/webflux-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/MessageServiceTests.java +++ b/samples/webflux-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/MessageServiceTests.java @@ -1,13 +1,15 @@ /* * Copyright 2019 Jérôme Wacongne. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the - * License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package com.c4_soft.springaddons.samples.webflux_jwtauthenticationtoken; @@ -15,29 +17,25 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; - import java.util.Map; import java.util.stream.Stream; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.oidc.StandardClaimNames; import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication; import org.springframework.security.test.context.TestSecurityContextHolder; - +import org.springframework.test.context.bean.override.mockito.MockitoBean; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockAuthentication; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithOpaqueToken; import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.AuthenticationSource; import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.ParameterizedAuthentication; import com.c4_soft.springaddons.security.oauth2.test.webflux.AddonsWebfluxComponentTest; - import reactor.core.publisher.Mono; /** @@ -47,94 +45,94 @@ */ @AddonsWebfluxComponentTest -@SpringBootTest(classes = { SecurityConfig.class, MessageService.class }) +@SpringBootTest(classes = {SecurityConfig.class, MessageService.class}) class MessageServiceTests { - // auto-wire tested component - @Autowired - private MessageService messageService; - - @Autowired - private WithOpaqueToken.AuthenticationFactory authFactory; - - // mock dependencies - @MockBean - SecretRepo secretRepo; - - @BeforeEach - public void setUp() { - when(secretRepo.findSecretByUsername(anyString())).thenReturn(Mono.just("incredible")); - } - - @Test() - void givenRequestIsAnonymous_whenGetSecret_thenThrows() { - // call tested components methods directly (do not use MockMvc nor WebTestClient) - assertThrows(Exception.class, () -> messageService.getSecret().block()); - } - - @Test() - void givenRequestIsAnonymous_whenGetGreet_thenThrows() { - assertThrows(Exception.class, () -> messageService.greet(null).block()); - } - - /*-------------------------------------*/ - /* @@WithMockBearerTokenAuthentication */ - /*-------------------------------------*/ - @Test() - @WithOpaqueToken("tonton-pirate.json") - void givenUserIsTontonPirate_whenGetSecret_thenThrows() { - assertThrows(Exception.class, () -> messageService.getSecret().block()); - } - - @Test - @WithOpaqueToken("ch4mp.json") - void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecret_thenReturnsSecret() { - assertThat(messageService.getSecret().block()).isEqualTo("incredible"); - } - - @ParameterizedTest - @MethodSource("identities") - void givenUserIsAuthenticated_whenGetGreet_thenReturnsGreeting(@ParameterizedAuthentication Authentication auth) { - assertThat(messageService.greet((BearerTokenAuthentication) auth).block()) - .isEqualTo("Hello %s! You are granted with %s.".formatted(auth.getName(), auth.getAuthorities())); - } - - Stream identities() { - return authFactory.authenticationsFrom("ch4mp.json", "tonton-pirate.json"); - } - - /*-------------------------*/ - /* @WithMockAuthentication */ - /*-------------------------*/ - @Test() - @WithMockAuthentication(authType = BearerTokenAuthentication.class, principalType = OAuth2AccessToken.class) - void givenUserIsAuthenticatedWithMockedAuthenticationButNotGrantedWithAuthorizedPersonnel_whenGetSecret_thenThrows() { - assertThrows(Exception.class, () -> messageService.getSecret().block()); - } - - @Test - @WithMockAuthentication(authType = BearerTokenAuthentication.class, principalType = OAuth2AccessToken.class, authorities = "ROLE_AUTHORIZED_PERSONNEL") - void givenUserIsAuthenticatedWithMockedAuthenticationAndGrantedWithAuthorizedPersonnel_whenGetSecret_thenReturnsSecret() { - final var auth = (BearerTokenAuthentication) TestSecurityContextHolder.getContext().getAuthentication(); - when(auth.getTokenAttributes()).thenReturn(Map.of(StandardClaimNames.PREFERRED_USERNAME, "ch4mpy")); - - assertThat(messageService.getSecret().block()).isEqualTo("incredible"); - } - - @ParameterizedTest - @AuthenticationSource({ - @WithMockAuthentication( - authType = BearerTokenAuthentication.class, - principalType = OAuth2AccessToken.class, - name = "Ch4mpy", - authorities = { "NICE", "AUTHOR" }), - @WithMockAuthentication( - authType = BearerTokenAuthentication.class, - principalType = OAuth2AccessToken.class, - name = "Tonton-Pirate", - authorities = { "UNCLE", "SKIPPER" }) }) - void givenUserIsAuthenticatedWithMockedAuthentication_whenGetGreet_thenReturnsGreeting(@ParameterizedAuthentication Authentication auth) { - assertThat(messageService.greet((BearerTokenAuthentication) auth).block()) - .isEqualTo("Hello %s! You are granted with %s.".formatted(auth.getName(), auth.getAuthorities())); - } + // auto-wire tested component + @Autowired + private MessageService messageService; + + @Autowired + private WithOpaqueToken.AuthenticationFactory authFactory; + + // mock dependencies + @MockitoBean + SecretRepo secretRepo; + + @BeforeEach + public void setUp() { + when(secretRepo.findSecretByUsername(anyString())).thenReturn(Mono.just("incredible")); + } + + @Test() + void givenRequestIsAnonymous_whenGetSecret_thenThrows() { + // call tested components methods directly (do not use MockMvc nor WebTestClient) + assertThrows(Exception.class, () -> messageService.getSecret().block()); + } + + @Test() + void givenRequestIsAnonymous_whenGetGreet_thenThrows() { + assertThrows(Exception.class, () -> messageService.greet(null).block()); + } + + /*-------------------------------------*/ + /* @@WithMockBearerTokenAuthentication */ + /*-------------------------------------*/ + @Test() + @WithOpaqueToken("tonton-pirate.json") + void givenUserIsTontonPirate_whenGetSecret_thenThrows() { + assertThrows(Exception.class, () -> messageService.getSecret().block()); + } + + @Test + @WithOpaqueToken("ch4mp.json") + void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecret_thenReturnsSecret() { + assertThat(messageService.getSecret().block()).isEqualTo("incredible"); + } + + @ParameterizedTest + @MethodSource("identities") + void givenUserIsAuthenticated_whenGetGreet_thenReturnsGreeting( + @ParameterizedAuthentication Authentication auth) { + assertThat(messageService.greet((BearerTokenAuthentication) auth).block()).isEqualTo( + "Hello %s! You are granted with %s.".formatted(auth.getName(), auth.getAuthorities())); + } + + Stream identities() { + return authFactory.authenticationsFrom("ch4mp.json", "tonton-pirate.json"); + } + + /*-------------------------*/ + /* @WithMockAuthentication */ + /*-------------------------*/ + @Test() + @WithMockAuthentication(authType = BearerTokenAuthentication.class, + principalType = OAuth2AccessToken.class) + void givenUserIsAuthenticatedWithMockedAuthenticationButNotGrantedWithAuthorizedPersonnel_whenGetSecret_thenThrows() { + assertThrows(Exception.class, () -> messageService.getSecret().block()); + } + + @Test + @WithMockAuthentication(authType = BearerTokenAuthentication.class, + principalType = OAuth2AccessToken.class, authorities = "ROLE_AUTHORIZED_PERSONNEL") + void givenUserIsAuthenticatedWithMockedAuthenticationAndGrantedWithAuthorizedPersonnel_whenGetSecret_thenReturnsSecret() { + final var auth = + (BearerTokenAuthentication) TestSecurityContextHolder.getContext().getAuthentication(); + when(auth.getTokenAttributes()) + .thenReturn(Map.of(StandardClaimNames.PREFERRED_USERNAME, "ch4mpy")); + + assertThat(messageService.getSecret().block()).isEqualTo("incredible"); + } + + @ParameterizedTest + @AuthenticationSource({@WithMockAuthentication(authType = BearerTokenAuthentication.class, + principalType = OAuth2AccessToken.class, name = "Ch4mpy", authorities = {"NICE", "AUTHOR"}), + @WithMockAuthentication(authType = BearerTokenAuthentication.class, + principalType = OAuth2AccessToken.class, name = "Tonton-Pirate", + authorities = {"UNCLE", "SKIPPER"})}) + void givenUserIsAuthenticatedWithMockedAuthentication_whenGetGreet_thenReturnsGreeting( + @ParameterizedAuthentication Authentication auth) { + assertThat(messageService.greet((BearerTokenAuthentication) auth).block()).isEqualTo( + "Hello %s! You are granted with %s.".formatted(auth.getName(), auth.getAuthorities())); + } } diff --git a/samples/webflux-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerAnnotatedTest.java b/samples/webflux-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerAnnotatedTest.java index 42637cb9c..b882f2c10 100644 --- a/samples/webflux-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerAnnotatedTest.java +++ b/samples/webflux-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerAnnotatedTest.java @@ -22,10 +22,10 @@ import org.junit.jupiter.params.provider.MethodSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.security.core.Authentication; import org.springframework.security.test.context.support.WithAnonymousUser; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithOpaqueToken; import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.ParameterizedAuthentication; import com.c4_soft.springaddons.security.oauth2.test.webflux.AutoConfigureAddonsWebfluxResourceServerSecurity; @@ -47,7 +47,7 @@ class GreetingControllerAnnotatedTest { // Mock controller injected dependencies - @MockBean + @MockitoBean private MessageService messageService; @Autowired diff --git a/samples/webflux-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerFluentApiTest.java b/samples/webflux-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerFluentApiTest.java index b1766faa6..cb0af0c06 100644 --- a/samples/webflux-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerFluentApiTest.java +++ b/samples/webflux-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerFluentApiTest.java @@ -1,35 +1,34 @@ /* * Copyright 2019 Jérôme Wacongne. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the - * License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package com.c4_soft.springaddons.samples.webflux_jwtauthenticationtoken; import static com.c4_soft.springaddons.security.oauth2.test.webflux.MockAuthenticationWebTestClientConfigurer.mockAuthentication; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers; - +import org.springframework.test.context.bean.override.mockito.MockitoBean; import com.c4_soft.springaddons.security.oauth2.test.webflux.AutoConfigureAddonsWebfluxResourceServerSecurity; import com.c4_soft.springaddons.security.oauth2.test.webflux.MockAuthenticationWebTestClientConfigurer; import com.c4_soft.springaddons.security.oauth2.test.webflux.WebTestClientSupport; import com.c4_soft.springaddons.security.oidc.OAuthentication; - import reactor.core.publisher.Mono; /** @@ -37,65 +36,73 @@ */ @WebFluxTest(GreetingController.class) @AutoConfigureAddonsWebfluxResourceServerSecurity -@Import({ SecurityConfig.class }) +@Import({SecurityConfig.class}) public class GreetingControllerFluentApiTest { - static final AnonymousAuthenticationToken ANONYMOUS = - new AnonymousAuthenticationToken("anonymous", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); - - @MockBean - private MessageService messageService; - - @Autowired - WebTestClientSupport api; - - @BeforeEach - public void setUp() { - when(messageService.greet(any())).thenAnswer(invocation -> { - final OAuthentication auth = invocation.getArgument(0, OAuthentication.class); - return Mono.just(String.format("Hello %s! You are granted with %s.", auth.getName(), auth.getAuthorities())); - }); - when(messageService.getSecret()).thenReturn(Mono.just("Secret message")); - } - - @Test - void givenRequestIsAnonymous_whenGetGreet_thenUnauthorized() throws Exception { - api.mutateWith(SecurityMockServerConfigurers.mockAuthentication(ANONYMOUS)).get("https://localhost/greet").expectStatus().isUnauthorized(); - } - - @Test - void givenUserIsAuthenticated_whenGetGreet_thenOk() throws Exception { - api.mutateWith(mockAuthentication(OAuthentication.class).name("user")).get("https://localhost/greet").expectBody(String.class) - .isEqualTo("Hello user! You are granted with []."); - } - - @Test - void givenUserIsCh4mpy_whenGetGreet_thenOk() throws Exception { - api.mutateWith(ch4mpy()).get("https://localhost/greet").expectBody(String.class) - .isEqualTo("Hello Ch4mpy! You are granted with [ROLE_AUTHORIZED_PERSONNEL]."); - } - - @Test - void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() throws Exception { - api.mutateWith(mockAuthentication(OAuthentication.class)).get("https://localhost/secured-route").expectStatus().isForbidden(); - } - - @Test - void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() throws Exception { - api.mutateWith(mockAuthentication(OAuthentication.class)).get("https://localhost/secured-method").expectStatus().isForbidden(); - } - - @Test - void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception { - api.mutateWith(ch4mpy()).get("https://localhost/secured-route").expectStatus().isOk(); - } - - @Test - void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception { - api.mutateWith(ch4mpy()).get("https://localhost/secured-method").expectStatus().isOk(); - } - - @SuppressWarnings("rawtypes") - private MockAuthenticationWebTestClientConfigurer ch4mpy() { - return mockAuthentication(OAuthentication.class).name("Ch4mpy").authorities("ROLE_AUTHORIZED_PERSONNEL"); - } + static final AnonymousAuthenticationToken ANONYMOUS = new AnonymousAuthenticationToken( + "anonymous", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); + + @MockitoBean + private MessageService messageService; + + @Autowired + WebTestClientSupport api; + + @BeforeEach + public void setUp() { + when(messageService.greet(any())).thenAnswer(invocation -> { + final OAuthentication auth = invocation.getArgument(0, OAuthentication.class); + return Mono.just(String.format("Hello %s! You are granted with %s.", auth.getName(), + auth.getAuthorities())); + }); + when(messageService.getSecret()).thenReturn(Mono.just("Secret message")); + } + + @Test + void givenRequestIsAnonymous_whenGetGreet_thenUnauthorized() throws Exception { + api.mutateWith(SecurityMockServerConfigurers.mockAuthentication(ANONYMOUS)) + .get("https://localhost/greet").expectStatus().isUnauthorized(); + } + + @Test + void givenUserIsAuthenticated_whenGetGreet_thenOk() throws Exception { + api.mutateWith(mockAuthentication(OAuthentication.class).name("user")) + .get("https://localhost/greet").expectBody(String.class) + .isEqualTo("Hello user! You are granted with []."); + } + + @Test + void givenUserIsCh4mpy_whenGetGreet_thenOk() throws Exception { + api.mutateWith(ch4mpy()).get("https://localhost/greet").expectBody(String.class) + .isEqualTo("Hello Ch4mpy! You are granted with [ROLE_AUTHORIZED_PERSONNEL]."); + } + + @Test + void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() + throws Exception { + api.mutateWith(mockAuthentication(OAuthentication.class)).get("https://localhost/secured-route") + .expectStatus().isForbidden(); + } + + @Test + void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() + throws Exception { + api.mutateWith(mockAuthentication(OAuthentication.class)) + .get("https://localhost/secured-method").expectStatus().isForbidden(); + } + + @Test + void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception { + api.mutateWith(ch4mpy()).get("https://localhost/secured-route").expectStatus().isOk(); + } + + @Test + void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception { + api.mutateWith(ch4mpy()).get("https://localhost/secured-method").expectStatus().isOk(); + } + + @SuppressWarnings("rawtypes") + private MockAuthenticationWebTestClientConfigurer ch4mpy() { + return mockAuthentication(OAuthentication.class).name("Ch4mpy") + .authorities("ROLE_AUTHORIZED_PERSONNEL"); + } } diff --git a/samples/webflux-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/MessageServiceTests.java b/samples/webflux-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/MessageServiceTests.java index f538863f9..31dd5da43 100644 --- a/samples/webflux-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/MessageServiceTests.java +++ b/samples/webflux-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/MessageServiceTests.java @@ -24,9 +24,9 @@ import org.junit.jupiter.params.provider.MethodSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.core.Authentication; import org.springframework.security.test.context.support.WithAnonymousUser; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithOpaqueToken; import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.ParameterizedAuthentication; import com.c4_soft.springaddons.security.oauth2.test.webflux.AddonsWebfluxComponentTest; @@ -52,7 +52,7 @@ class MessageServiceTests { WithOpaqueToken.AuthenticationFactory authFactory; // mock dependencies - @MockBean + @MockitoBean SecretRepo secretRepo; @BeforeEach diff --git a/samples/webflux-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerAnnotatedTest.java b/samples/webflux-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerAnnotatedTest.java index 1522361f5..6b12ea789 100644 --- a/samples/webflux-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerAnnotatedTest.java +++ b/samples/webflux-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerAnnotatedTest.java @@ -1,42 +1,40 @@ /* * Copyright 2019 Jérôme Wacongne. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the - * License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package com.c4_soft.springaddons.samples.webflux_jwtauthenticationtoken; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; - import java.util.stream.Stream; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.security.test.context.support.WithAnonymousUser; - +import org.springframework.test.context.bean.override.mockito.MockitoBean; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithJwt; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockAuthentication; import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.ParameterizedAuthentication; import com.c4_soft.springaddons.security.oauth2.test.webflux.AutoConfigureAddonsWebfluxResourceServerSecurity; import com.c4_soft.springaddons.security.oauth2.test.webflux.WebTestClientSupport; import com.c4_soft.springaddons.security.oidc.OAuthentication; - import reactor.core.publisher.Mono; /** @@ -46,90 +44,95 @@ */ @WebFluxTest(GreetingController.class) // Use WebFluxTest or WebMvcTest -@AutoConfigureAddonsWebfluxResourceServerSecurity // If your web-security depends on it, setup spring-addons security -@Import({ SecurityConfig.class }) // Import your web-security configuration +@AutoConfigureAddonsWebfluxResourceServerSecurity // If your web-security depends on it, setup + // spring-addons security +@Import({SecurityConfig.class}) // Import your web-security configuration class GreetingControllerAnnotatedTest { - // Mock controller injected dependencies - @MockBean - private MessageService messageService; - - @Autowired - WebTestClientSupport api; - - @Autowired - WithJwt.AuthenticationFactory authFactory; - - @BeforeEach - public void setUp() { - when(messageService.greet(any())).thenAnswer(invocation -> { - final JwtAuthenticationToken auth = invocation.getArgument(0, JwtAuthenticationToken.class); - return Mono.just(String.format("Hello %s! You are granted with %s.", auth.getName(), auth.getAuthorities())); - }); - when(messageService.getSecret()).thenReturn(Mono.just("Secret message")); - } - - @Test - @WithAnonymousUser - void givenRequestIsAnonymous_whenGetGreet_thenUnauthorized() throws Exception { - api.get("https://localhost/greet").expectStatus().isUnauthorized(); - } - - @ParameterizedTest - @MethodSource("auth0users") - void givenUserIsAuthenticated_whenGetGreet_thenOk(@ParameterizedAuthentication Authentication auth) throws Exception { - api.get("https://localhost/greet").expectBody(String.class) - .isEqualTo("Hello %s! You are granted with %s.".formatted(auth.getName(), auth.getAuthorities())); - } - - @Test - @WithMockAuthentication( - authType = JwtAuthenticationToken.class, - principalType = Jwt.class, - name = "Tonton Pirate", - authorities = "ROLE_AUTHORIZED_PERSONNEL") - void givenUserIsMockedAsCh4mpy_whenGetGreet_thenOk() throws Exception { - api.get("https://localhost/greet").expectBody(String.class).isEqualTo("Hello Tonton Pirate! You are granted with [ROLE_AUTHORIZED_PERSONNEL]."); - } - - @Test - @WithJwt("ch4mp.json") - void givenUserIsCh4mpy_whenGetGreet_thenOk() throws Exception { - api.get("https://localhost/greet").expectBody(String.class) - .isEqualTo("Hello ch4mp! You are granted with [USER_ROLES_EDITOR, ROLE_AUTHORIZED_PERSONNEL]."); - } - - @Test - @WithMockAuthentication(authType = JwtAuthenticationToken.class, principalType = Jwt.class) - void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() throws Exception { - api.get("https://localhost/secured-route").expectStatus().isForbidden(); - } - - @Test - @WithMockAuthentication(authType = JwtAuthenticationToken.class, principalType = Jwt.class, authorities = "ROLE_AUTHORIZED_PERSONNEL") - void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception { - api.get("https://localhost/secured-route").expectStatus().isOk(); - } - - @Test - @WithMockAuthentication(authType = JwtAuthenticationToken.class, principalType = Jwt.class) - void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() throws Exception { - api.get("https://localhost/secured-method").expectStatus().isForbidden(); - } - - @Test - @WithMockAuthentication(authType = JwtAuthenticationToken.class, principalType = Jwt.class, authorities = "ROLE_AUTHORIZED_PERSONNEL") - void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception { - api.get("https://localhost/secured-method").expectStatus().isOk(); - } - - /** - * @MethodSource for @ParameterizedTest - * - * @return a stream of {@link OAuthentication OAuthentication<OpenidClaimSet>} as defined by the Authentication converter in the security - * configuration - */ - Stream auth0users() { - return authFactory.authenticationsFrom("ch4mp.json", "tonton-pirate.json"); - } + // Mock controller injected dependencies + @MockitoBean + private MessageService messageService; + + @Autowired + WebTestClientSupport api; + + @Autowired + WithJwt.AuthenticationFactory authFactory; + + @BeforeEach + public void setUp() { + when(messageService.greet(any())).thenAnswer(invocation -> { + final JwtAuthenticationToken auth = invocation.getArgument(0, JwtAuthenticationToken.class); + return Mono.just(String.format("Hello %s! You are granted with %s.", auth.getName(), + auth.getAuthorities())); + }); + when(messageService.getSecret()).thenReturn(Mono.just("Secret message")); + } + + @Test + @WithAnonymousUser + void givenRequestIsAnonymous_whenGetGreet_thenUnauthorized() throws Exception { + api.get("https://localhost/greet").expectStatus().isUnauthorized(); + } + + @ParameterizedTest + @MethodSource("auth0users") + void givenUserIsAuthenticated_whenGetGreet_thenOk( + @ParameterizedAuthentication Authentication auth) throws Exception { + api.get("https://localhost/greet").expectBody(String.class).isEqualTo( + "Hello %s! You are granted with %s.".formatted(auth.getName(), auth.getAuthorities())); + } + + @Test + @WithMockAuthentication(authType = JwtAuthenticationToken.class, principalType = Jwt.class, + name = "Tonton Pirate", authorities = "ROLE_AUTHORIZED_PERSONNEL") + void givenUserIsMockedAsCh4mpy_whenGetGreet_thenOk() throws Exception { + api.get("https://localhost/greet").expectBody(String.class) + .isEqualTo("Hello Tonton Pirate! You are granted with [ROLE_AUTHORIZED_PERSONNEL]."); + } + + @Test + @WithJwt("ch4mp.json") + void givenUserIsCh4mpy_whenGetGreet_thenOk() throws Exception { + api.get("https://localhost/greet").expectBody(String.class).isEqualTo( + "Hello ch4mp! You are granted with [USER_ROLES_EDITOR, ROLE_AUTHORIZED_PERSONNEL]."); + } + + @Test + @WithMockAuthentication(authType = JwtAuthenticationToken.class, principalType = Jwt.class) + void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() + throws Exception { + api.get("https://localhost/secured-route").expectStatus().isForbidden(); + } + + @Test + @WithMockAuthentication(authType = JwtAuthenticationToken.class, principalType = Jwt.class, + authorities = "ROLE_AUTHORIZED_PERSONNEL") + void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception { + api.get("https://localhost/secured-route").expectStatus().isOk(); + } + + @Test + @WithMockAuthentication(authType = JwtAuthenticationToken.class, principalType = Jwt.class) + void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() + throws Exception { + api.get("https://localhost/secured-method").expectStatus().isForbidden(); + } + + @Test + @WithMockAuthentication(authType = JwtAuthenticationToken.class, principalType = Jwt.class, + authorities = "ROLE_AUTHORIZED_PERSONNEL") + void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception { + api.get("https://localhost/secured-method").expectStatus().isOk(); + } + + /** + * @MethodSource for @ParameterizedTest + * + * @return a stream of {@link OAuthentication OAuthentication<OpenidClaimSet>} as defined by + * the Authentication converter in the security configuration + */ + Stream auth0users() { + return authFactory.authenticationsFrom("ch4mp.json", "tonton-pirate.json"); + } } diff --git a/samples/webflux-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerFluentApiTest.java b/samples/webflux-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerFluentApiTest.java index ce60c379a..06ed45b8f 100644 --- a/samples/webflux-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerFluentApiTest.java +++ b/samples/webflux-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/GreetingControllerFluentApiTest.java @@ -1,36 +1,35 @@ /* * Copyright 2019 Jérôme Wacongne. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the - * License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package com.c4_soft.springaddons.samples.webflux_jwtauthenticationtoken; import static com.c4_soft.springaddons.security.oauth2.test.webflux.MockAuthenticationWebTestClientConfigurer.mockAuthentication; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers; - +import org.springframework.test.context.bean.override.mockito.MockitoBean; import com.c4_soft.springaddons.security.oauth2.test.webflux.AutoConfigureAddonsWebfluxResourceServerSecurity; import com.c4_soft.springaddons.security.oauth2.test.webflux.MockAuthenticationWebTestClientConfigurer; import com.c4_soft.springaddons.security.oauth2.test.webflux.WebTestClientSupport; - import reactor.core.publisher.Mono; /** @@ -38,59 +37,65 @@ */ @WebFluxTest(GreetingController.class) @AutoConfigureAddonsWebfluxResourceServerSecurity -@Import({ SecurityConfig.class }) +@Import({SecurityConfig.class}) public class GreetingControllerFluentApiTest { - private static final Authentication ANONYMOUS_AUTHENTICATION = - new AnonymousAuthenticationToken("anonymous", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); + private static final Authentication ANONYMOUS_AUTHENTICATION = new AnonymousAuthenticationToken( + "anonymous", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); - @MockBean - private MessageService messageService; + @MockitoBean + private MessageService messageService; - @Autowired - WebTestClientSupport api; + @Autowired + WebTestClientSupport api; - @BeforeEach - public void setUp() { - when(messageService.greet(any())).thenAnswer(invocation -> { - final JwtAuthenticationToken auth = invocation.getArgument(0, JwtAuthenticationToken.class); - return Mono.just(String.format("Hello %s! You are granted with %s.", auth.getName(), auth.getAuthorities())); - }); - when(messageService.getSecret()).thenReturn(Mono.just("Secret message")); - } + @BeforeEach + public void setUp() { + when(messageService.greet(any())).thenAnswer(invocation -> { + final JwtAuthenticationToken auth = invocation.getArgument(0, JwtAuthenticationToken.class); + return Mono.just(String.format("Hello %s! You are granted with %s.", auth.getName(), + auth.getAuthorities())); + }); + when(messageService.getSecret()).thenReturn(Mono.just("Secret message")); + } - @Test - void givenRequestIsUnauthorized_whenGetGreet_thenUnauthorized() throws Exception { - api.mutateWith(SecurityMockServerConfigurers.mockAuthentication(ANONYMOUS_AUTHENTICATION)).get("https://localhost/greet").expectStatus() - .isUnauthorized(); - } + @Test + void givenRequestIsUnauthorized_whenGetGreet_thenUnauthorized() throws Exception { + api.mutateWith(SecurityMockServerConfigurers.mockAuthentication(ANONYMOUS_AUTHENTICATION)) + .get("https://localhost/greet").expectStatus().isUnauthorized(); + } - @Test - void givenUserIsCh4mpy_whenGetGreet_thenOk() throws Exception { - api.mutateWith(ch4mpy()).get("https://localhost/greet").expectBody(String.class) - .isEqualTo("Hello Ch4mpy! You are granted with [ROLE_AUTHORIZED_PERSONNEL]."); - } + @Test + void givenUserIsCh4mpy_whenGetGreet_thenOk() throws Exception { + api.mutateWith(ch4mpy()).get("https://localhost/greet").expectBody(String.class) + .isEqualTo("Hello Ch4mpy! You are granted with [ROLE_AUTHORIZED_PERSONNEL]."); + } - @Test - void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() throws Exception { - api.mutateWith(mockAuthentication(JwtAuthenticationToken.class)).get("https://localhost/secured-route").expectStatus().isForbidden(); - } + @Test + void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() + throws Exception { + api.mutateWith(mockAuthentication(JwtAuthenticationToken.class)) + .get("https://localhost/secured-route").expectStatus().isForbidden(); + } - @Test - void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() throws Exception { - api.mutateWith(mockAuthentication(JwtAuthenticationToken.class)).get("https://localhost/secured-method").expectStatus().isForbidden(); - } + @Test + void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() + throws Exception { + api.mutateWith(mockAuthentication(JwtAuthenticationToken.class)) + .get("https://localhost/secured-method").expectStatus().isForbidden(); + } - @Test - void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception { - api.mutateWith(ch4mpy()).get("https://localhost/secured-route").expectStatus().isOk(); - } + @Test + void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception { + api.mutateWith(ch4mpy()).get("https://localhost/secured-route").expectStatus().isOk(); + } - @Test - void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception { - api.mutateWith(ch4mpy()).get("https://localhost/secured-method").expectStatus().isOk(); - } + @Test + void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception { + api.mutateWith(ch4mpy()).get("https://localhost/secured-method").expectStatus().isOk(); + } - private MockAuthenticationWebTestClientConfigurer ch4mpy() { - return mockAuthentication(JwtAuthenticationToken.class).name("Ch4mpy").authorities("ROLE_AUTHORIZED_PERSONNEL"); - } + private MockAuthenticationWebTestClientConfigurer ch4mpy() { + return mockAuthentication(JwtAuthenticationToken.class).name("Ch4mpy") + .authorities("ROLE_AUTHORIZED_PERSONNEL"); + } } diff --git a/samples/webflux-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/MessageServiceTests.java b/samples/webflux-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/MessageServiceTests.java index 5df31331b..4a631c566 100644 --- a/samples/webflux-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/MessageServiceTests.java +++ b/samples/webflux-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webflux_jwtauthenticationtoken/MessageServiceTests.java @@ -1,13 +1,15 @@ /* * Copyright 2019 Jérôme Wacongne. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the - * License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package com.c4_soft.springaddons.samples.webflux_jwtauthenticationtoken; @@ -16,18 +18,15 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; - import java.util.List; import java.util.Map; import java.util.stream.Stream; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.SimpleGrantedAuthority; @@ -35,12 +34,11 @@ import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.security.test.context.TestSecurityContextHolder; - +import org.springframework.test.context.bean.override.mockito.MockitoBean; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithJwt; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockAuthentication; import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.ParameterizedAuthentication; import com.c4_soft.springaddons.security.oauth2.test.webflux.AddonsWebfluxComponentTest; - import reactor.core.publisher.Mono; /** @@ -51,90 +49,97 @@ // Import security configuration and test component @AddonsWebfluxComponentTest -@SpringBootTest(classes = { SecurityConfig.class, MessageService.class }) +@SpringBootTest(classes = {SecurityConfig.class, MessageService.class}) class MessageServiceTests { - // auto-wire tested component - @Autowired - private MessageService messageService; - - @Autowired - WithJwt.AuthenticationFactory authFactory; - - // mock dependencies - @MockBean - SecretRepo secretRepo; - - @BeforeEach - public void setUp() { - when(secretRepo.findSecretByUsername(anyString())).thenReturn(Mono.just("incredible")); - } - - @Test() - void givenRequestIsAnonymous_whenGetSecret_thenThrows() { - // call tested components methods directly (do not use MockMvc nor WebTestClient) - assertThrows(Exception.class, () -> messageService.getSecret().block()); - } - - @Test() - void givenRequestIsAnonymous_whenGetGreet_thenThrows() { - assertThrows(Exception.class, () -> messageService.greet(null).block()); - } - - /*----------*/ - /* @WithJwt */ - /*----------*/ - @Test() - @WithJwt("tonton-pirate.json") - void givenUserIsTontonPirate_whenGetSecret_thenThrows() { - assertThrows(Exception.class, () -> messageService.getSecret().block()); - } - - @Test - @WithJwt("ch4mp.json") - void givenUserIsCh4mp_whenGetSecret_thenReturnsSecret() { - assertThat(messageService.getSecret().block()).isEqualTo("incredible"); - } - - @ParameterizedTest - @MethodSource("auth0users") - void givenUserIsPersona_whenGetGreet_thenReturnsGreeting(@ParameterizedAuthentication Authentication auth) { - final var jwtAuth = (JwtAuthenticationToken) auth; - assertThat(messageService.greet(jwtAuth).block()).isEqualTo("Hello %s! You are granted with %s.".formatted(auth.getName(), auth.getAuthorities())); - } - - Stream auth0users() { - return authFactory.authenticationsFrom("ch4mp.json", "tonton-pirate.json"); - } - - /*-------------------------*/ - /* @WithMockAuthentication */ - /*-------------------------*/ - @Test() - @WithMockAuthentication(authType = JwtAuthenticationToken.class, principalType = Jwt.class) - void givenUserIsAuthenticatedWithMockedAuthenticationButNotGrantedWithAuthorizedPersonnel_whenGetSecret_thenThrows() { - assertThrows(Exception.class, () -> messageService.getSecret().block()); - } - - @Test - @WithMockAuthentication(authType = JwtAuthenticationToken.class, principalType = Jwt.class, authorities = "ROLE_AUTHORIZED_PERSONNEL") - void givenUserIsAuthenticatedWithMockedAuthenticationAndGrantedWithAuthorizedPersonnel_whenGetSecret_thenReturnsSecret() { - final var auth = (JwtAuthenticationToken) TestSecurityContextHolder.getContext().getAuthentication(); - when(auth.getTokenAttributes()).thenReturn(Map.of(StandardClaimNames.PREFERRED_USERNAME, "ch4mpy")); - - assertThat(messageService.getSecret().block()).isEqualTo("incredible"); - } - - @Test - @WithMockAuthentication(authType = JwtAuthenticationToken.class, principalType = Jwt.class) - void givenUserIsAuthenticatedWithMockedAuthentication_whenGetGreet_thenReturnsGreeting() { - final var auth = mock(JwtAuthenticationToken.class); - final var token = mock(Jwt.class); - when(auth.getName()).thenReturn("ch4mpy"); - when(auth.getToken()).thenReturn(token); - when(auth.getAuthorities()).thenReturn(List.of(new SimpleGrantedAuthority("ROLE_AUTHORIZED_PERSONNEL"))); - - assertThat(messageService.greet(auth).block()).isEqualTo("Hello ch4mpy! You are granted with [ROLE_AUTHORIZED_PERSONNEL]."); - } + // auto-wire tested component + @Autowired + private MessageService messageService; + + @Autowired + WithJwt.AuthenticationFactory authFactory; + + // mock dependencies + @MockitoBean + SecretRepo secretRepo; + + @BeforeEach + public void setUp() { + when(secretRepo.findSecretByUsername(anyString())).thenReturn(Mono.just("incredible")); + } + + @Test() + void givenRequestIsAnonymous_whenGetSecret_thenThrows() { + // call tested components methods directly (do not use MockMvc nor WebTestClient) + assertThrows(Exception.class, () -> messageService.getSecret().block()); + } + + @Test() + void givenRequestIsAnonymous_whenGetGreet_thenThrows() { + assertThrows(Exception.class, () -> messageService.greet(null).block()); + } + + /*----------*/ + /* @WithJwt */ + /*----------*/ + @Test() + @WithJwt("tonton-pirate.json") + void givenUserIsTontonPirate_whenGetSecret_thenThrows() { + assertThrows(Exception.class, () -> messageService.getSecret().block()); + } + + @Test + @WithJwt("ch4mp.json") + void givenUserIsCh4mp_whenGetSecret_thenReturnsSecret() { + assertThat(messageService.getSecret().block()).isEqualTo("incredible"); + } + + @ParameterizedTest + @MethodSource("auth0users") + void givenUserIsPersona_whenGetGreet_thenReturnsGreeting( + @ParameterizedAuthentication Authentication auth) { + final var jwtAuth = (JwtAuthenticationToken) auth; + assertThat(messageService.greet(jwtAuth).block()).isEqualTo( + "Hello %s! You are granted with %s.".formatted(auth.getName(), auth.getAuthorities())); + } + + Stream auth0users() { + return authFactory.authenticationsFrom("ch4mp.json", "tonton-pirate.json"); + } + + /*-------------------------*/ + /* @WithMockAuthentication */ + /*-------------------------*/ + @Test() + @WithMockAuthentication(authType = JwtAuthenticationToken.class, principalType = Jwt.class) + void givenUserIsAuthenticatedWithMockedAuthenticationButNotGrantedWithAuthorizedPersonnel_whenGetSecret_thenThrows() { + assertThrows(Exception.class, () -> messageService.getSecret().block()); + } + + @Test + @WithMockAuthentication(authType = JwtAuthenticationToken.class, principalType = Jwt.class, + authorities = "ROLE_AUTHORIZED_PERSONNEL") + void givenUserIsAuthenticatedWithMockedAuthenticationAndGrantedWithAuthorizedPersonnel_whenGetSecret_thenReturnsSecret() { + final var auth = + (JwtAuthenticationToken) TestSecurityContextHolder.getContext().getAuthentication(); + when(auth.getTokenAttributes()) + .thenReturn(Map.of(StandardClaimNames.PREFERRED_USERNAME, "ch4mpy")); + + assertThat(messageService.getSecret().block()).isEqualTo("incredible"); + } + + @Test + @WithMockAuthentication(authType = JwtAuthenticationToken.class, principalType = Jwt.class) + void givenUserIsAuthenticatedWithMockedAuthentication_whenGetGreet_thenReturnsGreeting() { + final var auth = mock(JwtAuthenticationToken.class); + final var token = mock(Jwt.class); + when(auth.getName()).thenReturn("ch4mpy"); + when(auth.getToken()).thenReturn(token); + when(auth.getAuthorities()) + .thenReturn(List.of(new SimpleGrantedAuthority("ROLE_AUTHORIZED_PERSONNEL"))); + + assertThat(messageService.greet(auth).block()) + .isEqualTo("Hello ch4mpy! You are granted with [ROLE_AUTHORIZED_PERSONNEL]."); + } } diff --git a/samples/webflux-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webflux_oidcauthentication/GreetingControllerAnnotatedTest.java b/samples/webflux-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webflux_oidcauthentication/GreetingControllerAnnotatedTest.java index a50536dd8..ae062a814 100644 --- a/samples/webflux-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webflux_oidcauthentication/GreetingControllerAnnotatedTest.java +++ b/samples/webflux-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webflux_oidcauthentication/GreetingControllerAnnotatedTest.java @@ -1,31 +1,30 @@ /* * Copyright 2019 Jérôme Wacongne. * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the - * License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ package com.c4_soft.springaddons.samples.webflux_oidcauthentication; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; - +import org.springframework.test.context.bean.override.mockito.MockitoBean; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithJwt; import com.c4_soft.springaddons.security.oauth2.test.webflux.AutoConfigureAddonsWebfluxResourceServerSecurity; import com.c4_soft.springaddons.security.oauth2.test.webflux.WebTestClientSupport; import com.c4_soft.springaddons.security.oidc.OAuthentication; - import reactor.core.publisher.Mono; /** @@ -35,64 +34,70 @@ */ @WebFluxTest(GreetingController.class) // Use WebFluxTest or WebMvcTest -@AutoConfigureAddonsWebfluxResourceServerSecurity // If your web-security depends on it, setup spring-addons security -@Import({ SecurityConfig.class }) // Import your web-security configuration +@AutoConfigureAddonsWebfluxResourceServerSecurity // If your web-security depends on it, setup + // spring-addons security +@Import({SecurityConfig.class}) // Import your web-security configuration class GreetingControllerAnnotatedTest { - // Mock controller injected dependencies - @MockBean - private MessageService messageService; - - @Autowired - WebTestClientSupport api; - - @BeforeEach - public void setUp() { - when(messageService.greet(any())).thenAnswer(invocation -> { - final OAuthentication auth = invocation.getArgument(0, OAuthentication.class); - return Mono.just(String.format("Hello %s! You are granted with %s.", auth.getName(), auth.getAuthorities())); - }); - when(messageService.getSecret()).thenReturn(Mono.just("Secret message")); - } - - @Test - void givenRequestIsAnonymous_whenGetGreet_thenUnauthorized() throws Exception { - api.get("/greet").expectStatus().isUnauthorized(); - } - - @Test - @WithJwt("ch4mp.json") - void givenUserIAuthenticated_whenGetGreet_thenOk() throws Exception { - api.get("/greet").expectBody(String.class).isEqualTo("Hello ch4mp! You are granted with [USER_ROLES_EDITOR, ROLE_AUTHORIZED_PERSONNEL]."); - } - - @Test - @WithJwt("ch4mp.json") - void givenUserIsCh4mp_whenGetGreet_thenOk() throws Exception { - api.get("/greet").expectBody(String.class).isEqualTo("Hello ch4mp! You are granted with [USER_ROLES_EDITOR, ROLE_AUTHORIZED_PERSONNEL]."); - } - - @Test - @WithJwt("tonton-pirate.json") - void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() throws Exception { - api.get("/secured-route").expectStatus().isForbidden(); - } - - @Test - @WithJwt("ch4mp.json") - void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception { - api.get("/secured-route").expectStatus().isOk(); - } - - @Test - @WithJwt("tonton-pirate.json") - void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() throws Exception { - api.get("/secured-method").expectStatus().isForbidden(); - } - - @Test - @WithJwt("ch4mp.json") - void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception { - api.get("/secured-method").expectStatus().isOk(); - } + // Mock controller injected dependencies + @MockitoBean + private MessageService messageService; + + @Autowired + WebTestClientSupport api; + + @BeforeEach + public void setUp() { + when(messageService.greet(any())).thenAnswer(invocation -> { + final OAuthentication auth = invocation.getArgument(0, OAuthentication.class); + return Mono.just(String.format("Hello %s! You are granted with %s.", auth.getName(), + auth.getAuthorities())); + }); + when(messageService.getSecret()).thenReturn(Mono.just("Secret message")); + } + + @Test + void givenRequestIsAnonymous_whenGetGreet_thenUnauthorized() throws Exception { + api.get("/greet").expectStatus().isUnauthorized(); + } + + @Test + @WithJwt("ch4mp.json") + void givenUserIAuthenticated_whenGetGreet_thenOk() throws Exception { + api.get("/greet").expectBody(String.class).isEqualTo( + "Hello ch4mp! You are granted with [USER_ROLES_EDITOR, ROLE_AUTHORIZED_PERSONNEL]."); + } + + @Test + @WithJwt("ch4mp.json") + void givenUserIsCh4mp_whenGetGreet_thenOk() throws Exception { + api.get("/greet").expectBody(String.class).isEqualTo( + "Hello ch4mp! You are granted with [USER_ROLES_EDITOR, ROLE_AUTHORIZED_PERSONNEL]."); + } + + @Test + @WithJwt("tonton-pirate.json") + void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() + throws Exception { + api.get("/secured-route").expectStatus().isForbidden(); + } + + @Test + @WithJwt("ch4mp.json") + void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception { + api.get("/secured-route").expectStatus().isOk(); + } + + @Test + @WithJwt("tonton-pirate.json") + void givenUserIsNotGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() + throws Exception { + api.get("/secured-method").expectStatus().isForbidden(); + } + + @Test + @WithJwt("ch4mp.json") + void givenUserIsGrantedWithAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception { + api.get("/secured-method").expectStatus().isOk(); + } } diff --git a/samples/webflux-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webflux_oidcauthentication/MessageServiceTests.java b/samples/webflux-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webflux_oidcauthentication/MessageServiceTests.java index 757fda895..53959847d 100644 --- a/samples/webflux-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webflux_oidcauthentication/MessageServiceTests.java +++ b/samples/webflux-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webflux_oidcauthentication/MessageServiceTests.java @@ -28,10 +28,10 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.Authentication; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import com.c4_soft.springaddons.security.oauth2.test.AuthenticationFactoriesTestConf; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithJwt; import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.ParameterizedAuthentication; @@ -74,7 +74,7 @@ class MessageServiceTests { WithJwt.AuthenticationFactory authFactory; // mock dependencies - @MockBean + @MockitoBean SecretRepo secretRepo; @BeforeEach diff --git a/samples/webmvc-introspecting-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingController.java b/samples/webmvc-introspecting-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingController.java index b1cb03e12..975d05e65 100644 --- a/samples/webmvc-introspecting-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingController.java +++ b/samples/webmvc-introspecting-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingController.java @@ -1,13 +1,11 @@ package com.c4_soft.springaddons.samples.webmvc_jwtauthenticationtoken; import java.util.Map; - import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; - import lombok.RequiredArgsConstructor; @RestController diff --git a/samples/webmvc-introspecting-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/MessageService.java b/samples/webmvc-introspecting-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/MessageService.java index 5a5d1fd4c..713458924 100644 --- a/samples/webmvc-introspecting-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/MessageService.java +++ b/samples/webmvc-introspecting-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/MessageService.java @@ -16,7 +16,6 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication; import org.springframework.stereotype.Service; - import lombok.RequiredArgsConstructor; @Service diff --git a/samples/webmvc-introspecting-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/SecurityConfig.java b/samples/webmvc-introspecting-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/SecurityConfig.java index 128bd8cf3..3a826340d 100644 --- a/samples/webmvc-introspecting-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/SecurityConfig.java +++ b/samples/webmvc-introspecting-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/SecurityConfig.java @@ -6,7 +6,6 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; - import com.c4_soft.springaddons.security.oidc.starter.synchronised.resourceserver.ResourceServerExpressionInterceptUrlRegistryPostProcessor; @Configuration diff --git a/samples/webmvc-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingControllerAnnotatedTest.java b/samples/webmvc-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingControllerAnnotatedTest.java index e196f7ea6..baa686820 100644 --- a/samples/webmvc-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingControllerAnnotatedTest.java +++ b/samples/webmvc-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingControllerAnnotatedTest.java @@ -15,22 +15,19 @@ import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import java.util.stream.Stream; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication; import org.springframework.security.test.context.support.WithAnonymousUser; - +import org.springframework.test.context.bean.override.mockito.MockitoBean; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockAuthentication; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithOpaqueToken; import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.ParameterizedAuthentication; @@ -49,7 +46,7 @@ class GreetingControllerAnnotatedTest { // Mock controller injected dependencies - @MockBean + @MockitoBean private MessageService messageService; @Autowired diff --git a/samples/webmvc-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingControllerFluentApiTest.java b/samples/webmvc-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingControllerFluentApiTest.java index d22bf5c04..e1fb4d4c0 100644 --- a/samples/webmvc-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingControllerFluentApiTest.java +++ b/samples/webmvc-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingControllerFluentApiTest.java @@ -18,16 +18,14 @@ import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.anonymous; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication; - +import org.springframework.test.context.bean.override.mockito.MockitoBean; import com.c4_soft.springaddons.security.oauth2.test.webmvc.AutoConfigureAddonsWebmvcResourceServerSecurity; import com.c4_soft.springaddons.security.oauth2.test.webmvc.MockAuthenticationRequestPostProcessor; import com.c4_soft.springaddons.security.oauth2.test.webmvc.MockMvcSupport; @@ -40,7 +38,7 @@ @Import({ SecurityConfig.class }) class GreetingControllerFluentApiTest { - @MockBean + @MockitoBean private MessageService messageService; @Autowired diff --git a/samples/webmvc-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/MessageServiceTests.java b/samples/webmvc-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/MessageServiceTests.java index 767bdb583..c53b00944 100644 --- a/samples/webmvc-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/MessageServiceTests.java +++ b/samples/webmvc-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/MessageServiceTests.java @@ -16,25 +16,22 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; - import java.util.List; import java.util.Map; import java.util.stream.Stream; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.oidc.StandardClaimNames; import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication; import org.springframework.security.test.context.TestSecurityContextHolder; - +import org.springframework.test.context.bean.override.mockito.MockitoBean; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockAuthentication; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithOpaqueToken; import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.ParameterizedAuthentication; @@ -59,7 +56,7 @@ class MessageServiceTests { WithOpaqueToken.AuthenticationFactory authFactory; // mock dependencies - @MockBean + @MockitoBean SecretRepo secretRepo; @BeforeEach diff --git a/samples/webmvc-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/SampleApiIntegrationTest.java b/samples/webmvc-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/SampleApiIntegrationTest.java index 9283487d7..2398da96d 100644 --- a/samples/webmvc-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/SampleApiIntegrationTest.java +++ b/samples/webmvc-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/SampleApiIntegrationTest.java @@ -2,7 +2,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; @@ -12,7 +11,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.security.test.context.support.WithAnonymousUser; - import com.c4_soft.springaddons.security.oauth2.test.annotations.WithOpaqueToken; import com.c4_soft.springaddons.security.oauth2.test.webmvc.AddonsWebmvcTestConf; import com.c4_soft.springaddons.security.oauth2.test.webmvc.MockMvcSupport; diff --git a/samples/webmvc-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/SecretRepoTest.java b/samples/webmvc-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/SecretRepoTest.java index f0d0bd9c5..efa3ad09a 100644 --- a/samples/webmvc-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/SecretRepoTest.java +++ b/samples/webmvc-introspecting-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/SecretRepoTest.java @@ -13,12 +13,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; - import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.security.test.context.support.WithAnonymousUser; - import com.c4_soft.springaddons.security.oauth2.test.annotations.WithOpaqueToken; import com.c4_soft.springaddons.security.oauth2.test.webmvc.AddonsWebmvcComponentTest; diff --git a/samples/webmvc-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/GreetingControllerAnnotatedTest.java b/samples/webmvc-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/GreetingControllerAnnotatedTest.java index 81801b7aa..8f8098496 100644 --- a/samples/webmvc-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/GreetingControllerAnnotatedTest.java +++ b/samples/webmvc-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/GreetingControllerAnnotatedTest.java @@ -24,10 +24,10 @@ import org.junit.jupiter.params.provider.MethodSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.security.core.Authentication; import org.springframework.security.test.context.support.WithAnonymousUser; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithOpaqueToken; import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.ParameterizedAuthentication; import com.c4_soft.springaddons.security.oauth2.test.webmvc.AutoConfigureAddonsWebmvcResourceServerSecurity; @@ -43,7 +43,7 @@ @Import({SecurityConfig.class}) class GreetingControllerAnnotatedTest { - @MockBean + @MockitoBean private MessageService messageService; @Autowired diff --git a/samples/webmvc-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/MessageServiceTests.java b/samples/webmvc-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/MessageServiceTests.java index dda99e27e..8de94867f 100644 --- a/samples/webmvc-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/MessageServiceTests.java +++ b/samples/webmvc-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/MessageServiceTests.java @@ -21,9 +21,9 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.test.context.support.WithAnonymousUser; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithOpaqueToken; import com.c4_soft.springaddons.security.oauth2.test.webmvc.AddonsWebmvcComponentTest; import com.c4_soft.springaddons.security.oidc.OAuthentication; @@ -45,7 +45,7 @@ class MessageServiceTests { private MessageService messageService; // mock dependencies - @MockBean + @MockitoBean SecretRepo secretRepo; @BeforeEach diff --git a/samples/webmvc-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/SampleApiIntegrationTest.java b/samples/webmvc-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/SampleApiIntegrationTest.java index c2fae37ba..367c291e1 100644 --- a/samples/webmvc-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/SampleApiIntegrationTest.java +++ b/samples/webmvc-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/SampleApiIntegrationTest.java @@ -2,7 +2,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; @@ -11,7 +10,6 @@ import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; - import com.c4_soft.springaddons.security.oauth2.test.annotations.WithOpaqueToken; import com.c4_soft.springaddons.security.oauth2.test.webmvc.AddonsWebmvcTestConf; import com.c4_soft.springaddons.security.oauth2.test.webmvc.MockMvcSupport; diff --git a/samples/webmvc-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/SecretRepoTest.java b/samples/webmvc-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/SecretRepoTest.java index be1a859b8..8f1ab6741 100644 --- a/samples/webmvc-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/SecretRepoTest.java +++ b/samples/webmvc-introspecting-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/SecretRepoTest.java @@ -13,12 +13,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; - import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.security.test.context.support.WithAnonymousUser; - import com.c4_soft.springaddons.security.oauth2.test.annotations.WithOpaqueToken; import com.c4_soft.springaddons.security.oauth2.test.webmvc.AddonsWebmvcComponentTest; diff --git a/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/GreetingController.java b/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/GreetingController.java index 0896739ab..d1323dc82 100644 --- a/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/GreetingController.java +++ b/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/GreetingController.java @@ -1,7 +1,6 @@ package com.c4_soft.springaddons.samples.webmvc_jwtauthenticationtoken_jpa_authorities; import java.util.Map; - import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.web.bind.annotation.GetMapping; diff --git a/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/PersistedGrantedAuthoritiesRetriever.java b/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/PersistedGrantedAuthoritiesRetriever.java index 89c0825ce..e1e382649 100644 --- a/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/PersistedGrantedAuthoritiesRetriever.java +++ b/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/PersistedGrantedAuthoritiesRetriever.java @@ -15,13 +15,11 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; - import org.springframework.lang.NonNull; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.jwt.JwtClaimNames; import org.springframework.transaction.annotation.Transactional; - import com.c4_soft.springaddons.security.oidc.starter.ClaimSetAuthoritiesConverter; /** diff --git a/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/SecurityConfig.java b/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/SecurityConfig.java index 4194f5444..44e17143c 100644 --- a/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/SecurityConfig.java +++ b/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/SecurityConfig.java @@ -6,7 +6,6 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; - import com.c4_soft.springaddons.security.oidc.starter.ClaimSetAuthoritiesConverter; import com.c4_soft.springaddons.security.oidc.starter.synchronised.resourceserver.ResourceServerExpressionInterceptUrlRegistryPostProcessor; diff --git a/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/UserAuthority.java b/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/UserAuthority.java index e8dc53f47..6a4b9a7cf 100644 --- a/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/UserAuthority.java +++ b/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/UserAuthority.java @@ -12,7 +12,6 @@ package com.c4_soft.springaddons.samples.webmvc_jwtauthenticationtoken_jpa_authorities; import java.io.Serializable; - import jakarta.persistence.EmbeddedId; import jakarta.persistence.Entity; import lombok.Data; diff --git a/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/UserAuthorityId.java b/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/UserAuthorityId.java index 6e53eef31..2c5378eb6 100644 --- a/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/UserAuthorityId.java +++ b/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/UserAuthorityId.java @@ -12,7 +12,6 @@ package com.c4_soft.springaddons.samples.webmvc_jwtauthenticationtoken_jpa_authorities; import java.io.Serializable; - import jakarta.persistence.Column; import jakarta.persistence.Embeddable; import lombok.AllArgsConstructor; diff --git a/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/UserAuthorityRepository.java b/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/UserAuthorityRepository.java index da0b81832..34dca55fd 100644 --- a/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/UserAuthorityRepository.java +++ b/samples/webmvc-jwt-default-jpa-authorities/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/UserAuthorityRepository.java @@ -12,7 +12,6 @@ package com.c4_soft.springaddons.samples.webmvc_jwtauthenticationtoken_jpa_authorities; import java.util.Collection; - import org.springframework.cache.annotation.Cacheable; import org.springframework.data.jpa.repository.JpaRepository; diff --git a/samples/webmvc-jwt-default-jpa-authorities/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/GreetingControllerAnnotatedTest.java b/samples/webmvc-jwt-default-jpa-authorities/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/GreetingControllerAnnotatedTest.java index 4e472ae8b..20deaeba4 100644 --- a/samples/webmvc-jwt-default-jpa-authorities/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/GreetingControllerAnnotatedTest.java +++ b/samples/webmvc-jwt-default-jpa-authorities/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/GreetingControllerAnnotatedTest.java @@ -15,36 +15,25 @@ import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import java.util.stream.Stream; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInstance; -import org.junit.jupiter.api.TestInstance.Lifecycle; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; - -import com.c4_soft.springaddons.security.oauth2.test.AuthenticationFactoriesTestConf; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithJwt; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockAuthentication; import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.ParameterizedAuthentication; -import com.c4_soft.springaddons.security.oauth2.test.webmvc.AddonsWebmvcTestConf; import com.c4_soft.springaddons.security.oauth2.test.webmvc.AutoConfigureAddonsWebmvcResourceServerSecurity; import com.c4_soft.springaddons.security.oauth2.test.webmvc.MockMvcSupport; import com.c4_soft.springaddons.security.oidc.starter.properties.SpringAddonsOidcProperties; -import com.c4_soft.springaddons.security.oidc.starter.synchronised.SpringAddonsOidcBeans; -import com.c4_soft.springaddons.security.oidc.starter.synchronised.resourceserver.SpringAddonsOidcResourceServerBeans; - import jakarta.persistence.EntityManagerFactory; /** @@ -55,7 +44,7 @@ @AutoConfigureAddonsWebmvcResourceServerSecurity class GreetingControllerAnnotatedTest { - @MockBean + @MockitoBean private MessageService messageService; @Autowired @@ -67,7 +56,7 @@ class GreetingControllerAnnotatedTest { @Autowired SpringAddonsOidcProperties springAddonsOidcProperties; - @MockBean(name = "entityManagerFactory") + @MockitoBean(name = "entityManagerFactory") EntityManagerFactory entityManagerFactory; @BeforeEach diff --git a/samples/webmvc-jwt-default-jpa-authorities/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/GreetingControllerFluentApiTest.java b/samples/webmvc-jwt-default-jpa-authorities/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/GreetingControllerFluentApiTest.java index 9973c159c..f69f0590c 100644 --- a/samples/webmvc-jwt-default-jpa-authorities/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/GreetingControllerFluentApiTest.java +++ b/samples/webmvc-jwt-default-jpa-authorities/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/GreetingControllerFluentApiTest.java @@ -17,21 +17,18 @@ import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; - +import org.springframework.test.context.bean.override.mockito.MockitoBean; import com.c4_soft.springaddons.security.oauth2.test.webmvc.AutoConfigureAddonsWebmvcResourceServerSecurity; import com.c4_soft.springaddons.security.oauth2.test.webmvc.MockAuthenticationRequestPostProcessor; import com.c4_soft.springaddons.security.oauth2.test.webmvc.MockMvcSupport; - import jakarta.persistence.EntityManagerFactory; /** @@ -42,16 +39,16 @@ @Import({ SecurityConfig.class }) class GreetingControllerFluentApiTest { - @MockBean + @MockitoBean private MessageService messageService; @Autowired MockMvcSupport api; - @MockBean + @MockitoBean UserAuthorityRepository userAuthorityRepository; - @MockBean(name = "entityManagerFactory") + @MockitoBean(name = "entityManagerFactory") EntityManagerFactory entityManagerFactory; @BeforeEach diff --git a/samples/webmvc-jwt-default-jpa-authorities/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/MessageServiceTests.java b/samples/webmvc-jwt-default-jpa-authorities/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/MessageServiceTests.java index 4e036bafa..32f81cd5a 100644 --- a/samples/webmvc-jwt-default-jpa-authorities/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/MessageServiceTests.java +++ b/samples/webmvc-jwt-default-jpa-authorities/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/MessageServiceTests.java @@ -15,7 +15,6 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; - import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.TestConfiguration; @@ -25,7 +24,6 @@ import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.security.test.context.TestSecurityContextHolder; - import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockAuthentication; import com.c4_soft.springaddons.security.oauth2.test.webmvc.AutoConfigureAddonsWebmvcMinimalSecurity; diff --git a/samples/webmvc-jwt-default-jpa-authorities/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/TestUserAuthorityRepositoryConf.java b/samples/webmvc-jwt-default-jpa-authorities/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/TestUserAuthorityRepositoryConf.java index f03187b12..92c937352 100644 --- a/samples/webmvc-jwt-default-jpa-authorities/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/TestUserAuthorityRepositoryConf.java +++ b/samples/webmvc-jwt-default-jpa-authorities/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken_jpa_authorities/TestUserAuthorityRepositoryConf.java @@ -2,9 +2,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; - import java.util.List; - import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; diff --git a/samples/webmvc-jwt-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/BasicAuthSecurityConfig.java b/samples/webmvc-jwt-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/BasicAuthSecurityConfig.java index 154f7b2fa..b5a86f67f 100644 --- a/samples/webmvc-jwt-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/BasicAuthSecurityConfig.java +++ b/samples/webmvc-jwt-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/BasicAuthSecurityConfig.java @@ -1,13 +1,11 @@ package com.c4_soft.springaddons.samples.webmvc_jwtauthenticationtoken; import static org.springframework.security.config.Customizer.withDefaults; - import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; - import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; @@ -35,14 +33,12 @@ import org.springframework.web.reactive.function.client.ExchangeFilterFunctions; import org.springframework.web.reactive.function.client.WebClient; import org.springframework.web.util.UriComponentsBuilder; - import com.c4_soft.springaddons.security.oidc.starter.properties.SpringAddonsOidcProperties; import com.c4_soft.springaddons.security.oidc.starter.properties.SpringAddonsOidcProperties.OpenidProviderProperties; import com.c4_soft.springaddons.security.oidc.starter.synchronised.ServletConfigurationSupport; import com.c4_soft.springaddons.security.oidc.starter.synchronised.resourceserver.ResourceServerExpressionInterceptUrlRegistryPostProcessor; import com.c4_soft.springaddons.security.oidc.starter.synchronised.resourceserver.ResourceServerSynchronizedHttpSecurityPostProcessor; import com.fasterxml.jackson.annotation.JsonProperty; - import jakarta.servlet.http.HttpServletRequest; import lombok.Data; diff --git a/samples/webmvc-jwt-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingController.java b/samples/webmvc-jwt-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingController.java index 18b19267e..12c3fa1e3 100644 --- a/samples/webmvc-jwt-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingController.java +++ b/samples/webmvc-jwt-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingController.java @@ -1,13 +1,11 @@ package com.c4_soft.springaddons.samples.webmvc_jwtauthenticationtoken; import java.util.Map; - import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; - import lombok.RequiredArgsConstructor; @RestController diff --git a/samples/webmvc-jwt-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/MessageService.java b/samples/webmvc-jwt-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/MessageService.java index ab2147753..744f06178 100644 --- a/samples/webmvc-jwt-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/MessageService.java +++ b/samples/webmvc-jwt-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/MessageService.java @@ -16,7 +16,6 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.stereotype.Service; - import lombok.RequiredArgsConstructor; @Service diff --git a/samples/webmvc-jwt-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/OAuth2SecurityConfig.java b/samples/webmvc-jwt-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/OAuth2SecurityConfig.java index 8b74bb77d..dea9183a2 100644 --- a/samples/webmvc-jwt-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/OAuth2SecurityConfig.java +++ b/samples/webmvc-jwt-default/src/main/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/OAuth2SecurityConfig.java @@ -6,7 +6,6 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; - import com.c4_soft.springaddons.security.oidc.starter.synchronised.resourceserver.ResourceServerExpressionInterceptUrlRegistryPostProcessor; @Configuration diff --git a/samples/webmvc-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingControllerAnnotatedTest.java b/samples/webmvc-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingControllerAnnotatedTest.java index faf99c57f..9054942a7 100644 --- a/samples/webmvc-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingControllerAnnotatedTest.java +++ b/samples/webmvc-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingControllerAnnotatedTest.java @@ -15,23 +15,20 @@ import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import java.util.stream.Stream; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.security.test.context.support.WithAnonymousUser; - +import org.springframework.test.context.bean.override.mockito.MockitoBean; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithJwt; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockAuthentication; import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.AuthenticationSource; @@ -51,7 +48,7 @@ class GreetingControllerAnnotatedTest { // Mock controller injected dependencies - @MockBean + @MockitoBean private MessageService messageService; @Autowired diff --git a/samples/webmvc-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingControllerFluentApiTest.java b/samples/webmvc-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingControllerFluentApiTest.java index a6863d718..6063bc290 100644 --- a/samples/webmvc-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingControllerFluentApiTest.java +++ b/samples/webmvc-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/GreetingControllerFluentApiTest.java @@ -17,17 +17,15 @@ import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; - +import org.springframework.test.context.bean.override.mockito.MockitoBean; import com.c4_soft.springaddons.security.oauth2.test.webmvc.AutoConfigureAddonsWebmvcResourceServerSecurity; import com.c4_soft.springaddons.security.oauth2.test.webmvc.MockAuthenticationRequestPostProcessor; import com.c4_soft.springaddons.security.oauth2.test.webmvc.MockMvcSupport; @@ -40,7 +38,7 @@ @Import({ OAuth2SecurityConfig.class }) class GreetingControllerFluentApiTest { - @MockBean + @MockitoBean private MessageService messageService; @Autowired diff --git a/samples/webmvc-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/MessageServiceTests.java b/samples/webmvc-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/MessageServiceTests.java index 3cb4dab64..4ee7af04e 100644 --- a/samples/webmvc-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/MessageServiceTests.java +++ b/samples/webmvc-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/MessageServiceTests.java @@ -15,21 +15,18 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; - import java.util.Map; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.core.oidc.StandardClaimNames; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.security.test.context.TestSecurityContextHolder; import org.springframework.security.test.context.support.WithAnonymousUser; - +import org.springframework.test.context.bean.override.mockito.MockitoBean; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithJwt; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockAuthentication; import com.c4_soft.springaddons.security.oauth2.test.webmvc.AddonsWebmvcComponentTest; @@ -50,7 +47,7 @@ class MessageServiceTests { private MessageService messageService; // mock dependencies - @MockBean + @MockitoBean SecretRepo secretRepo; @BeforeEach diff --git a/samples/webmvc-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/SampleApiIntegrationTest.java b/samples/webmvc-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/SampleApiIntegrationTest.java index 10e89a2a2..dcf740c52 100644 --- a/samples/webmvc-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/SampleApiIntegrationTest.java +++ b/samples/webmvc-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/SampleApiIntegrationTest.java @@ -3,7 +3,6 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; @@ -12,7 +11,6 @@ import org.springframework.context.annotation.Import; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.test.web.servlet.MockMvc; - import com.c4_soft.springaddons.security.oauth2.test.annotations.WithJwt; import com.c4_soft.springaddons.security.oauth2.test.webmvc.AddonsWebmvcTestConf; diff --git a/samples/webmvc-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/SecretRepoTest.java b/samples/webmvc-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/SecretRepoTest.java index 40ff39a71..eaa56ce60 100644 --- a/samples/webmvc-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/SecretRepoTest.java +++ b/samples/webmvc-jwt-default/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken/SecretRepoTest.java @@ -13,11 +13,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; - import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; - import com.c4_soft.springaddons.security.oauth2.test.annotations.WithJwt; import com.c4_soft.springaddons.security.oauth2.test.webmvc.AddonsWebmvcComponentTest; diff --git a/samples/webmvc-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/GreetingControllerAnnotatedTest.java b/samples/webmvc-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/GreetingControllerAnnotatedTest.java index c6589fc3b..12b3bbf78 100644 --- a/samples/webmvc-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/GreetingControllerAnnotatedTest.java +++ b/samples/webmvc-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/GreetingControllerAnnotatedTest.java @@ -21,8 +21,8 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithJwt; import com.c4_soft.springaddons.security.oauth2.test.webmvc.AutoConfigureAddonsWebmvcResourceServerSecurity; import com.c4_soft.springaddons.security.oauth2.test.webmvc.MockMvcSupport; @@ -37,7 +37,7 @@ @Import({SecurityConfig.class}) class GreetingControllerAnnotatedTest { - @MockBean + @MockitoBean private MessageService messageService; @Autowired diff --git a/samples/webmvc-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/MessageServiceTests.java b/samples/webmvc-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/MessageServiceTests.java index 31404a1ac..3a450b24b 100644 --- a/samples/webmvc-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/MessageServiceTests.java +++ b/samples/webmvc-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/MessageServiceTests.java @@ -24,9 +24,9 @@ import org.junit.jupiter.params.provider.MethodSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.Authentication; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import com.c4_soft.springaddons.security.oauth2.test.annotations.WithJwt; import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.ParameterizedAuthentication; import com.c4_soft.springaddons.security.oauth2.test.webmvc.AddonsWebmvcComponentTest; @@ -52,7 +52,7 @@ class MessageServiceTests { WithJwt.AuthenticationFactory authFactory; // mock dependencies - @MockBean + @MockitoBean SecretRepo secretRepo; @BeforeEach diff --git a/samples/webmvc-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/SampleApiIntegrationTest.java b/samples/webmvc-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/SampleApiIntegrationTest.java index 35f0430bb..8fe39d95f 100644 --- a/samples/webmvc-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/SampleApiIntegrationTest.java +++ b/samples/webmvc-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/SampleApiIntegrationTest.java @@ -2,9 +2,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import java.util.stream.Stream; - import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; @@ -18,7 +16,6 @@ import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.test.context.support.WithAnonymousUser; - import com.c4_soft.springaddons.security.oauth2.test.annotations.WithJwt; import com.c4_soft.springaddons.security.oauth2.test.annotations.parameterized.ParameterizedAuthentication; import com.c4_soft.springaddons.security.oauth2.test.webmvc.AddonsWebmvcTestConf; diff --git a/samples/webmvc-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/SecretRepoTest.java b/samples/webmvc-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/SecretRepoTest.java index 38bbc1464..e12d09a3a 100644 --- a/samples/webmvc-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/SecretRepoTest.java +++ b/samples/webmvc-jwt-oauthentication/src/test/java/com/c4_soft/springaddons/samples/webmvc_oidcauthentication/SecretRepoTest.java @@ -13,12 +13,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; - import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.security.test.context.support.WithAnonymousUser; - import com.c4_soft.springaddons.security.oauth2.test.annotations.WithJwt; import com.c4_soft.springaddons.security.oauth2.test.webmvc.AddonsWebmvcComponentTest; diff --git a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AddonsWebfluxComponentTest.java b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AddonsWebfluxComponentTest.java index 6b80cd74d..e400c5a88 100644 --- a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AddonsWebfluxComponentTest.java +++ b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AddonsWebfluxComponentTest.java @@ -4,9 +4,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - import org.springframework.boot.autoconfigure.EnableAutoConfiguration; - import com.c4_soft.springaddons.security.oauth2.test.webmvc.AutoConfigureAddonsWebmvcResourceServerSecurity; /** diff --git a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AddonsWebfluxTestConf.java b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AddonsWebfluxTestConf.java index 801c6fddd..107595c32 100644 --- a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AddonsWebfluxTestConf.java +++ b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AddonsWebfluxTestConf.java @@ -3,13 +3,10 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; - import java.util.ArrayList; - import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Scope; @@ -20,15 +17,14 @@ import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder; import org.springframework.security.oauth2.server.resource.introspection.ReactiveOpaqueTokenIntrospector; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.server.ServerWebExchange; - import com.c4_soft.springaddons.security.oauth2.test.AuthenticationFactoriesTestConf; import com.c4_soft.springaddons.security.oauth2.test.webmvc.AddonsWebmvcTestConf; import com.c4_soft.springaddons.security.oidc.starter.properties.SpringAddonsOidcProperties; import com.c4_soft.springaddons.security.oidc.starter.properties.condition.configuration.IsNotServlet; import com.c4_soft.springaddons.security.oidc.starter.properties.condition.configuration.IsOidcResourceServerCondition; - import reactor.core.publisher.Mono; @Conditional({ IsOidcResourceServerCondition.class, IsNotServlet.class }) @@ -36,13 +32,13 @@ @ImportAutoConfiguration(classes = { WebTestClientProperties.class, AuthenticationFactoriesTestConf.class }, exclude = { AddonsWebmvcTestConf.class }) public class AddonsWebfluxTestConf { - @MockBean + @MockitoBean ReactiveJwtDecoder jwtDecoder; - @MockBean + @MockitoBean ReactiveAuthenticationManagerResolver reactiveAuthenticationManagerResolver; - @MockBean + @MockitoBean ReactiveOpaqueTokenIntrospector introspector; @ConditionalOnMissingBean @@ -66,7 +62,7 @@ InMemoryReactiveClientRegistrationRepository clientRegistrationRepository() { return clientRegistrationRepository; } - @MockBean + @MockitoBean ReactiveOAuth2AuthorizedClientService oAuth2AuthorizedClientService; @Bean diff --git a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AuthenticationConfigurer.java b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AuthenticationConfigurer.java index d185ef6a4..61965cc53 100644 --- a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AuthenticationConfigurer.java +++ b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AuthenticationConfigurer.java @@ -20,7 +20,6 @@ import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClientConfigurer; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; - import com.c4_soft.springaddons.security.oauth2.test.AuthenticationBuilder; /** diff --git a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AutoConfigureAddonsWebfluxClientSecurity.java b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AutoConfigureAddonsWebfluxClientSecurity.java index f42535b33..fe792229e 100644 --- a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AutoConfigureAddonsWebfluxClientSecurity.java +++ b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AutoConfigureAddonsWebfluxClientSecurity.java @@ -4,9 +4,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - import org.springframework.boot.autoconfigure.ImportAutoConfiguration; - import com.c4_soft.springaddons.security.oauth2.test.webmvc.AddonsWebmvcComponentTest; import com.c4_soft.springaddons.security.oauth2.test.webmvc.AutoConfigureAddonsWebmvcMinimalSecurity; import com.c4_soft.springaddons.security.oauth2.test.webmvc.AutoConfigureAddonsWebmvcResourceServerSecurity; diff --git a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AutoConfigureAddonsWebfluxMinimalSecurity.java b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AutoConfigureAddonsWebfluxMinimalSecurity.java index 926d1a0b8..6d16c1fdc 100644 --- a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AutoConfigureAddonsWebfluxMinimalSecurity.java +++ b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AutoConfigureAddonsWebfluxMinimalSecurity.java @@ -4,13 +4,11 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; - import com.c4_soft.springaddons.security.oauth2.test.AuthenticationFactoriesTestConf; import com.c4_soft.springaddons.security.oauth2.test.webmvc.AddonsWebmvcComponentTest; import com.c4_soft.springaddons.security.oauth2.test.webmvc.AutoConfigureAddonsWebmvcResourceServerSecurity; diff --git a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AutoConfigureAddonsWebfluxResourceServerSecurity.java b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AutoConfigureAddonsWebfluxResourceServerSecurity.java index 6268bfd3a..5c429fbf5 100644 --- a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AutoConfigureAddonsWebfluxResourceServerSecurity.java +++ b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/AutoConfigureAddonsWebfluxResourceServerSecurity.java @@ -4,9 +4,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - import org.springframework.boot.autoconfigure.ImportAutoConfiguration; - import com.c4_soft.springaddons.security.oidc.starter.reactive.resourceserver.ReactiveSpringAddonsOidcResourceServerBeans; import com.c4_soft.springaddons.security.oidc.starter.synchronised.resourceserver.SpringAddonsOidcResourceServerBeans; diff --git a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/MockAuthenticationWebTestClientConfigurer.java b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/MockAuthenticationWebTestClientConfigurer.java index 65a1b26b7..40798deb7 100644 --- a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/MockAuthenticationWebTestClientConfigurer.java +++ b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/MockAuthenticationWebTestClientConfigurer.java @@ -13,15 +13,12 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; - import java.util.Collection; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; - import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.SimpleGrantedAuthority; - import com.c4_soft.springaddons.security.oauth2.test.Defaults; public class MockAuthenticationWebTestClientConfigurer implements AuthenticationConfigurer { diff --git a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/WebTestClientSupport.java b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/WebTestClientSupport.java index 15f2f4966..c84670dde 100644 --- a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/WebTestClientSupport.java +++ b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webflux/WebTestClientSupport.java @@ -12,13 +12,11 @@ package com.c4_soft.springaddons.security.oauth2.test.webflux; import java.nio.charset.Charset; - import org.springframework.http.MediaType; import org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; import org.springframework.test.web.reactive.server.WebTestClientConfigurer; - import com.c4_soft.springaddons.security.oidc.starter.properties.Csrf; import com.c4_soft.springaddons.security.oidc.starter.properties.SpringAddonsOidcProperties; diff --git a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AddonsWebmvcComponentTest.java b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AddonsWebmvcComponentTest.java index d32fba43e..da9812d09 100644 --- a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AddonsWebmvcComponentTest.java +++ b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AddonsWebmvcComponentTest.java @@ -4,9 +4,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - import org.springframework.boot.autoconfigure.EnableAutoConfiguration; - import com.c4_soft.springaddons.security.oauth2.test.webflux.AutoConfigureAddonsWebfluxClientSecurity; /** diff --git a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AddonsWebmvcTestConf.java b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AddonsWebmvcTestConf.java index f3f6fef1a..1994275f9 100644 --- a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AddonsWebmvcTestConf.java +++ b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AddonsWebmvcTestConf.java @@ -15,9 +15,7 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; - import java.util.ArrayList; - import org.springframework.beans.factory.ObjectFactory; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; @@ -26,7 +24,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.boot.autoconfigure.web.ServerProperties; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Scope; import org.springframework.security.authentication.AuthenticationManagerResolver; @@ -36,13 +33,12 @@ import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; - import com.c4_soft.springaddons.security.oauth2.test.AuthenticationFactoriesTestConf; import com.c4_soft.springaddons.security.oauth2.test.webflux.AddonsWebfluxTestConf; import com.c4_soft.springaddons.security.oidc.starter.properties.SpringAddonsOidcProperties; import com.c4_soft.springaddons.test.support.web.SerializationHelper; - import jakarta.servlet.http.HttpServletRequest; /** @@ -53,13 +49,13 @@ @ImportAutoConfiguration(classes = { MockMvcProperties.class, AuthenticationFactoriesTestConf.class }, exclude = { AddonsWebfluxTestConf.class }) public class AddonsWebmvcTestConf { - @MockBean + @MockitoBean JwtDecoder jwtDecoder; - @MockBean + @MockitoBean AuthenticationManagerResolver jwtIssuerAuthenticationManagerResolver; - @MockBean + @MockitoBean OpaqueTokenIntrospector introspector; @ConditionalOnMissingBean @@ -81,7 +77,7 @@ InMemoryClientRegistrationRepository clientRegistrationRepository() { return clientRegistrationRepository; } - @MockBean + @MockitoBean OAuth2AuthorizedClientService oAuth2AuthorizedClientService; @Bean diff --git a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AuthenticationRequestPostProcessor.java b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AuthenticationRequestPostProcessor.java index 1dea7d4ba..75331fbc8 100644 --- a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AuthenticationRequestPostProcessor.java +++ b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AuthenticationRequestPostProcessor.java @@ -15,7 +15,6 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.core.Authentication; import org.springframework.test.web.servlet.request.RequestPostProcessor; - import com.c4_soft.springaddons.security.oauth2.test.AuthenticationBuilder; /** diff --git a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AutoConfigureAddonsWebmvcClientSecurity.java b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AutoConfigureAddonsWebmvcClientSecurity.java index 504182491..36a1729ab 100644 --- a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AutoConfigureAddonsWebmvcClientSecurity.java +++ b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AutoConfigureAddonsWebmvcClientSecurity.java @@ -4,9 +4,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - import org.springframework.boot.autoconfigure.ImportAutoConfiguration; - import com.c4_soft.springaddons.security.oauth2.test.webflux.AutoConfigureAddonsWebfluxClientSecurity; import com.c4_soft.springaddons.security.oidc.starter.synchronised.client.SpringAddonsOidcClientWithLoginBeans; diff --git a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AutoConfigureAddonsWebmvcMinimalSecurity.java b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AutoConfigureAddonsWebmvcMinimalSecurity.java index f7cd6dd12..31f999a31 100644 --- a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AutoConfigureAddonsWebmvcMinimalSecurity.java +++ b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AutoConfigureAddonsWebmvcMinimalSecurity.java @@ -4,13 +4,11 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; - import com.c4_soft.springaddons.security.oauth2.test.AuthenticationFactoriesTestConf; import com.c4_soft.springaddons.security.oauth2.test.webflux.AutoConfigureAddonsWebfluxClientSecurity; import com.c4_soft.springaddons.security.oidc.starter.properties.SpringAddonsOidcProperties; diff --git a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AutoConfigureAddonsWebmvcResourceServerSecurity.java b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AutoConfigureAddonsWebmvcResourceServerSecurity.java index 88fd812c5..ac7383ae8 100644 --- a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AutoConfigureAddonsWebmvcResourceServerSecurity.java +++ b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/AutoConfigureAddonsWebmvcResourceServerSecurity.java @@ -4,9 +4,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - import org.springframework.boot.autoconfigure.ImportAutoConfiguration; - import com.c4_soft.springaddons.security.oauth2.test.webflux.AutoConfigureAddonsWebfluxClientSecurity; import com.c4_soft.springaddons.security.oidc.starter.synchronised.resourceserver.SpringAddonsOidcResourceServerBeans; diff --git a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/MockAuthenticationRequestPostProcessor.java b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/MockAuthenticationRequestPostProcessor.java index b6a3ae1e1..3fb836166 100644 --- a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/MockAuthenticationRequestPostProcessor.java +++ b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/MockAuthenticationRequestPostProcessor.java @@ -13,7 +13,6 @@ package com.c4_soft.springaddons.security.oauth2.test.webmvc; import org.springframework.security.core.Authentication; - import com.c4_soft.springaddons.security.oauth2.test.Defaults; import com.c4_soft.springaddons.security.oauth2.test.MockAuthenticationBuilder; diff --git a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/MockMvcProperties.java b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/MockMvcProperties.java index 72da161af..b96283777 100644 --- a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/MockMvcProperties.java +++ b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/MockMvcProperties.java @@ -2,7 +2,6 @@ import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.context.properties.ConfigurationProperties; - import lombok.Data; @Data diff --git a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/MockMvcSupport.java b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/MockMvcSupport.java index 34bd16413..580770abf 100644 --- a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/MockMvcSupport.java +++ b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/MockMvcSupport.java @@ -13,12 +13,10 @@ import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.request; - import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Optional; - import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.context.annotation.Scope; @@ -31,7 +29,6 @@ import org.springframework.test.web.servlet.request.RequestPostProcessor; import org.springframework.util.Assert; import org.springframework.web.servlet.DispatcherServlet; - import com.c4_soft.springaddons.security.oidc.starter.properties.Csrf; import com.c4_soft.springaddons.security.oidc.starter.properties.SpringAddonsOidcProperties; import com.c4_soft.springaddons.test.support.web.SerializationHelper; diff --git a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/SecurityContextRequestPostProcessorSupport.java b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/SecurityContextRequestPostProcessorSupport.java index 31b2bb511..658ec5724 100644 --- a/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/SecurityContextRequestPostProcessorSupport.java +++ b/spring-addons-starter-oidc-test/src/main/java/com/c4_soft/springaddons/security/oauth2/test/webmvc/SecurityContextRequestPostProcessorSupport.java @@ -7,7 +7,6 @@ import org.springframework.security.test.web.support.WebTestUtils; import org.springframework.security.web.context.HttpRequestResponseHolder; import org.springframework.security.web.context.SecurityContextRepository; - import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; diff --git a/spring-addons-starter-oidc/src/main/java/com/c4_soft/springaddons/security/oidc/starter/reactive/ReactiveConfigurationSupport.java b/spring-addons-starter-oidc/src/main/java/com/c4_soft/springaddons/security/oidc/starter/reactive/ReactiveConfigurationSupport.java index 6d358f39b..2411a755c 100644 --- a/spring-addons-starter-oidc/src/main/java/com/c4_soft/springaddons/security/oidc/starter/reactive/ReactiveConfigurationSupport.java +++ b/spring-addons-starter-oidc/src/main/java/com/c4_soft/springaddons/security/oidc/starter/reactive/ReactiveConfigurationSupport.java @@ -15,9 +15,6 @@ import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.server.context.NoOpServerSecurityContextRepository; import org.springframework.security.web.server.csrf.CookieServerCsrfTokenRepository; -import org.springframework.security.web.server.csrf.CsrfToken; -import org.springframework.security.web.server.csrf.ServerCsrfTokenRequestAttributeHandler; -import org.springframework.security.web.server.csrf.XorServerCsrfTokenRequestAttributeHandler; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.reactive.CorsWebFilter; import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; @@ -169,46 +166,14 @@ public static ServerHttpSecurity configureState(ServerHttpSecurity http, boolean withDefaults(); break; case COOKIE_ACCESSIBLE_FROM_JS: - // adapted from - // https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html#csrf-integration-javascript-spa - csrf.csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse()) - .csrfTokenRequestHandler(new SpaCsrfTokenRequestHandler()); + // https://docs.spring.io/spring-security/reference/reactive/exploits/csrf.html#webflux-csrf-configure-custom-repository + // the default is now XorServerCsrfTokenRequestAttributeHandler + // https://docs.spring.io/spring-security/reference/reactive/exploits/csrf.html#webflux-csrf-configure-request-handler + csrf.csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse()); break; } }); return http; } - - /** - * Adapted from - * https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html#csrf-integration-javascript-spa - */ - static final class SpaCsrfTokenRequestHandler extends ServerCsrfTokenRequestAttributeHandler { - private final ServerCsrfTokenRequestAttributeHandler delegate = - new XorServerCsrfTokenRequestAttributeHandler(); - - @Override - public void handle(ServerWebExchange exchange, Mono csrfToken) { - /* - * Always use XorCsrfTokenRequestAttributeHandler to provide BREACH protection of the - * CsrfToken when it is rendered in the response body. - */ - this.delegate.handle(exchange, csrfToken); - } - - @Override - public Mono resolveCsrfTokenValue(ServerWebExchange exchange, CsrfToken csrfToken) { - /* - * If the request contains a X-XSRF-TOKEN header, use it. This applies when a single-page - * application includes the header value automatically, which was obtained via a cookie - * containing the raw CsrfToken. In all other cases (e.g. if the request contains a request - * parameter), use XorCsrfTokenRequestAttributeHandler to resolve the CsrfToken. This applies - * when a server-side rendered form includes the _csrf request parameter as a hidden input. - */ - return Mono - .justOrEmpty(exchange.getRequest().getHeaders().getFirst(csrfToken.getHeaderName())) - .switchIfEmpty(this.delegate.resolveCsrfTokenValue(exchange, csrfToken)); - } - } } diff --git a/spring-addons-starter-oidc/src/main/java/com/c4_soft/springaddons/security/oidc/starter/synchronised/ServletConfigurationSupport.java b/spring-addons-starter-oidc/src/main/java/com/c4_soft/springaddons/security/oidc/starter/synchronised/ServletConfigurationSupport.java index c270f0ce7..499e38b58 100644 --- a/spring-addons-starter-oidc/src/main/java/com/c4_soft/springaddons/security/oidc/starter/synchronised/ServletConfigurationSupport.java +++ b/spring-addons-starter-oidc/src/main/java/com/c4_soft/springaddons/security/oidc/starter/synchronised/ServletConfigurationSupport.java @@ -1,7 +1,6 @@ package com.c4_soft.springaddons.security.oidc.starter.synchronised; import static org.springframework.security.config.Customizer.withDefaults; -import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; @@ -10,10 +9,8 @@ import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; -import org.springframework.lang.NonNull; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import org.springframework.security.web.csrf.CookieCsrfTokenRepository; import org.springframework.security.web.csrf.CsrfToken; import org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler; @@ -24,7 +21,6 @@ import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; -import org.springframework.web.filter.OncePerRequestFilter; import com.c4_soft.springaddons.security.oidc.starter.properties.CorsProperties; import com.c4_soft.springaddons.security.oidc.starter.properties.Csrf; import com.c4_soft.springaddons.security.oidc.starter.properties.SpringAddonsOidcProperties; @@ -33,8 +29,6 @@ import com.c4_soft.springaddons.security.oidc.starter.synchronised.client.ClientSynchronizedHttpSecurityPostProcessor; import com.c4_soft.springaddons.security.oidc.starter.synchronised.resourceserver.ResourceServerExpressionInterceptUrlRegistryPostProcessor; import com.c4_soft.springaddons.security.oidc.starter.synchronised.resourceserver.ResourceServerSynchronizedHttpSecurityPostProcessor; -import jakarta.servlet.FilterChain; -import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @@ -162,11 +156,9 @@ public static HttpSecurity configureState(HttpSecurity http, boolean isStatless, case SESSION: break; case COOKIE_ACCESSIBLE_FROM_JS: - // Taken from - // https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html#csrf-integration-javascript-spa-configuration + // https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html#csrf-integration-javascript configurer.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) .csrfTokenRequestHandler(new SpaCsrfTokenRequestHandler()); - http.addFilterAfter(new CsrfCookieFilter(), BasicAuthenticationFilter.class); break; } }); @@ -174,12 +166,9 @@ public static HttpSecurity configureState(HttpSecurity http, boolean isStatless, return http; } - /** - * Copied from - * https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html#csrf-integration-javascript-spa-configuration - */ - static final class SpaCsrfTokenRequestHandler extends CsrfTokenRequestAttributeHandler { - private final CsrfTokenRequestHandler delegate = new XorCsrfTokenRequestAttributeHandler(); + static final class SpaCsrfTokenRequestHandler implements CsrfTokenRequestHandler { + private final CsrfTokenRequestHandler plain = new CsrfTokenRequestAttributeHandler(); + private final CsrfTokenRequestHandler xor = new XorCsrfTokenRequestAttributeHandler(); @Override public void handle(HttpServletRequest request, HttpServletResponse response, @@ -188,44 +177,27 @@ public void handle(HttpServletRequest request, HttpServletResponse response, * Always use XorCsrfTokenRequestAttributeHandler to provide BREACH protection of the * CsrfToken when it is rendered in the response body. */ - this.delegate.handle(request, response, csrfToken); + this.xor.handle(request, response, csrfToken); + /* + * Render the token value to a cookie by causing the deferred token to be loaded. + */ + csrfToken.get(); } @Override public String resolveCsrfTokenValue(HttpServletRequest request, CsrfToken csrfToken) { + String headerValue = request.getHeader(csrfToken.getHeaderName()); /* * If the request contains a request header, use CsrfTokenRequestAttributeHandler to resolve * the CsrfToken. This applies when a single-page application includes the header value * automatically, which was obtained via a cookie containing the raw CsrfToken. - */ - final var csrfHeader = request.getHeader(csrfToken.getHeaderName()); - if (StringUtils.hasText(csrfHeader)) { - return csrfHeader; - } - /* + * * In all other cases (e.g. if the request contains a request parameter), use * XorCsrfTokenRequestAttributeHandler to resolve the CsrfToken. This applies when a * server-side rendered form includes the _csrf request parameter as a hidden input. */ - return this.delegate.resolveCsrfTokenValue(request, csrfToken); - } - } - - /** - * Copied from - * https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html#csrf-integration-javascript-spa-configuration - */ - static final class CsrfCookieFilter extends OncePerRequestFilter { - - @Override - protected void doFilterInternal(@NonNull HttpServletRequest request, - @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) - throws ServletException, IOException { - CsrfToken csrfToken = (CsrfToken) request.getAttribute("_csrf"); - // Render the token value to a cookie by causing the deferred token to be loaded - csrfToken.getToken(); - - filterChain.doFilter(request, response); + return (StringUtils.hasText(headerValue) ? this.plain : this.xor) + .resolveCsrfTokenValue(request, csrfToken); } } }