Skip to content

Commit

Permalink
Apply Spring Security 6 CSRF configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
ch4mpy committed Jan 17, 2025
1 parent 3cf52bd commit 825329a
Show file tree
Hide file tree
Showing 73 changed files with 701 additions and 848 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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")
Expand All @@ -42,7 +39,7 @@ class GreetingControllerTest {
static final AnonymousAuthenticationToken ANONYMOUS =
new AnonymousAuthenticationToken("anonymous", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));

@MockBean
@MockitoBean
ReactiveAuthenticationManagerResolver<ServerWebExchange> authenticationManagerResolver;

@Autowired
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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)
Expand All @@ -43,7 +40,7 @@ class ReactiveResourceServerApplicationTests {
static final AnonymousAuthenticationToken ANONYMOUS =
new AnonymousAuthenticationToken("anonymous", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));

@MockBean
@MockitoBean
ReactiveAuthenticationManagerResolver<ServerWebExchange> authenticationManagerResolver;

@Autowired
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<HttpServletRequest> authenticationManagerResolver;

@Autowired
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<HttpServletRequest> authenticationManagerResolver;

@Autowired
Expand Down
Original file line number Diff line number Diff line change
@@ -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;

/**
Expand All @@ -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();
}
}
Loading

0 comments on commit 825329a

Please sign in to comment.