ch4mpy
2023-02-16 08:47:54 -10:00
parent f996314508
commit 03c3de438c
17 changed files with 1300 additions and 0 deletions

View File

@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>spring-security-oauth2-testing</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<groupId>com.baeldung.spring-security-modules.testing</groupId>
<artifactId>servlet-resource-server</artifactId>
<name>servlet-resource-server</name>
<description>Demo project for Spring Boot servlet resource-server</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.c4-soft.springaddons</groupId>
<artifactId>spring-addons-oauth2-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,116 @@
package com.baeldung;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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.web.SecurityFilterChain;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.RequiredArgsConstructor;
@SpringBootApplication
public class ServletResourceServerApplication {
public static void main(String[] args) {
SpringApplication.run(ServletResourceServerApplication.class, args);
}
@Configuration
@EnableMethodSecurity
@EnableWebSecurity
static class SecurityConf {
@Bean
SecurityFilterChain filterChain(HttpSecurity http, Converter<Jwt, Collection<GrantedAuthority>> authoritiesConverter) throws Exception {
// @formatter:off
http.oauth2ResourceServer().jwt().jwtAuthenticationConverter(jwt -> new JwtAuthenticationToken(jwt, authoritiesConverter.convert(jwt)));
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().csrf().disable();
http.exceptionHandling().authenticationEntryPoint((request, response, authException) -> {
response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"Restricted Content\"");
response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
});
http.authorizeHttpRequests()
.requestMatchers("/secured-route").hasRole("AUTHORIZED_PERSONNEL")
.anyRequest().authenticated();
// @formatter:on
return http.build();
}
static interface AuthoritiesConverter extends Converter<Jwt, Collection<GrantedAuthority>> {
}
@Bean
AuthoritiesConverter realmRoles2AuthoritiesConverter() {
return (Jwt jwt) -> {
final var realmRoles = Optional.of(jwt.getClaimAsMap("realm_access")).orElse(Map.of());
@SuppressWarnings("unchecked")
final var roles = (List<String>) realmRoles.getOrDefault("roles", List.of());
return roles.stream().map(SimpleGrantedAuthority::new).map(GrantedAuthority.class::cast).toList();
};
}
}
@Service
public static class MessageService {
public String greet() {
final var who = (JwtAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
final var claims = who.getTokenAttributes();
return "Hello %s! You are granted with %s.".formatted(
claims.getOrDefault(StandardClaimNames.PREFERRED_USERNAME, claims.get(StandardClaimNames.SUB)),
who.getAuthorities());
}
@PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')")
public String getSecret() {
return "Only authorized personnel can read that";
}
}
@RestController
@RequiredArgsConstructor
public static class GreetingController {
private final MessageService messageService;
@GetMapping("/greet")
public ResponseEntity<String> greet() {
return ResponseEntity.ok(messageService.greet());
}
@GetMapping("/secured-route")
public ResponseEntity<String> securedRoute() {
return ResponseEntity.ok(messageService.getSecret());
}
@GetMapping("/secured-method")
@PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')")
public ResponseEntity<String> securedMethod() {
return ResponseEntity.ok(messageService.getSecret());
}
}
}

View File

@@ -0,0 +1 @@
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://localhost:8443/realms/master

View File

@@ -0,0 +1,79 @@
package com.baeldung;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.test.context.support.WithAnonymousUser;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.baeldung.ServletResourceServerApplication.MessageService;
import com.c4_soft.springaddons.security.oauth2.test.annotations.OpenIdClaims;
import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockJwtAuth;
@Import({ MessageService.class })
@ExtendWith(SpringExtension.class)
@EnableMethodSecurity
class MessageServiceUnitTest {
@Autowired
MessageService messageService;
/*----------------------------------------------------------------------------*/
/* greet() */
/* Expects a JwtAuthenticationToken to be retrieved from the security-context */
/*----------------------------------------------------------------------------*/
@Test
void givenSecurityContextIsNotSet_whenGreet_thenThrowsAuthenticationCredentialsNotFoundException() {
assertThrows(AuthenticationCredentialsNotFoundException.class, () -> messageService.getSecret());
}
@Test
@WithAnonymousUser
void givenUserIsNotAuthenticated_whenGreet_thenThrowsAccessDeniedException() {
assertThrows(AccessDeniedException.class, () -> messageService.getSecret());
}
@Test
@WithMockJwtAuth(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy"))
void givenSecurityContextIsPopulatedWithJwtAuthenticationToken_whenGreet_thenReturnGreetingWithPreferredUsernameAndAuthorities() {
assertEquals("Hello ch4mpy! You are granted with [admin, ROLE_AUTHORIZED_PERSONNEL].", messageService.greet());
}
@Test
@WithMockUser(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, username = "ch4mpy")
void givenSecurityContextIsPopulatedWithUsernamePasswordAuthenticationToken_whenGreet_thenThrowsClassCastException() {
assertThrows(ClassCastException.class, () -> messageService.greet());
}
/*--------------------------------------------------------------------*/
/* getSecret() */
/* is secured with "@PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')")" */
/*--------------------------------------------------------------------*/
@Test
@WithAnonymousUser
void givenUserIsNotAuthenticated_whenGetSecret_thenThrowsAccessDeniedException() {
assertThrows(AccessDeniedException.class, () -> messageService.getSecret());
}
@Test
@WithMockJwtAuth(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy"))
void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecret_thenReturnSecret() {
assertEquals("Only authorized personnel can read that", messageService.getSecret());
}
@Test
@WithMockJwtAuth(authorities = { "admin" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy"))
void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecret_thenThrowsAccessDeniedException() {
assertThrows(AccessDeniedException.class, () -> messageService.getSecret());
}
}

View File

@@ -0,0 +1,114 @@
package com.baeldung;
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;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.security.test.context.support.WithAnonymousUser;
import org.springframework.test.web.servlet.MockMvc;
import com.c4_soft.springaddons.security.oauth2.test.annotations.OpenIdClaims;
import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockJwtAuth;
@SpringBootTest(webEnvironment = WebEnvironment.MOCK)
@AutoConfigureMockMvc
class ServletResourceServerApplicationIntegrationTest {
@Autowired
MockMvc api;
/*-----------------------------------------------------------------------------*/
/* /greet */
/* This end-point secured with ".anyRequest().authenticated()" in SecurityConf */
/*-----------------------------------------------------------------------------*/
@Test
@WithAnonymousUser
void givenUserIsNotAuthenticated_whenGetGreet_thenUnauthorized() throws Exception {
// @formatter:off
api.perform(get("/greet"))
.andExpect(status().isUnauthorized());
// @formatter:on
}
@Test
@WithMockJwtAuth(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy"))
void givenUserIsAuthenticated_whenGetGreet_thenOk() throws Exception {
// @formatter:off
api.perform(get("/greet"))
.andExpect(status().isOk())
.andExpect(content().string("Hello ch4mpy! You are granted with [admin, ROLE_AUTHORIZED_PERSONNEL]."));
// @formatter:on
}
/*---------------------------------------------------------------------------------------------------------------------*/
/* /secured-route */
/* This end-point is secured with ".requestMatchers("/secured-route").hasRole("AUTHORIZED_PERSONNEL")" in SecurityConf */
/*---------------------------------------------------------------------------------------------------------------------*/
@Test
@WithAnonymousUser
void givenUserIsNotAuthenticated_whenGetSecuredRoute_thenUnauthorized() throws Exception {
// @formatter:off
api.perform(get("/secured-route"))
.andExpect(status().isUnauthorized());
// @formatter:on
}
@Test
@WithMockJwtAuth("ROLE_AUTHORIZED_PERSONNEL")
void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception {
// @formatter:off
api.perform(get("/secured-route"))
.andExpect(status().isOk())
.andExpect(content().string("Only authorized personnel can read that"));
// @formatter:on
}
@Test
@WithMockJwtAuth("admin")
void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() throws Exception {
// @formatter:off
api.perform(get("/secured-route"))
.andExpect(status().isForbidden());
// @formatter:on
}
/*---------------------------------------------------------------------------------------------------------*/
/* /secured-method */
/* This end-point is secured with "@PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')")" on @Controller method */
/*---------------------------------------------------------------------------------------------------------*/
@Test
@WithAnonymousUser
void givenUserIsNotAuthenticated_whenGetSecuredMethod_thenUnauthorized() throws Exception {
// @formatter:off
api.perform(get("/secured-method"))
.andExpect(status().isUnauthorized());
// @formatter:on
}
@Test
@WithMockJwtAuth("ROLE_AUTHORIZED_PERSONNEL")
void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception {
// @formatter:off
api.perform(get("/secured-method"))
.andExpect(status().isOk())
.andExpect(content().string("Only authorized personnel can read that"));
// @formatter:on
}
@Test
@WithMockJwtAuth("admin")
void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() throws Exception {
// @formatter:off
api.perform(get("/secured-method"))
.andExpect(status().isForbidden());
// @formatter:on
}
}

View File

@@ -0,0 +1,131 @@
package com.baeldung;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
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.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.security.test.context.support.WithAnonymousUser;
import org.springframework.test.web.servlet.MockMvc;
import com.baeldung.ServletResourceServerApplication.GreetingController;
import com.baeldung.ServletResourceServerApplication.MessageService;
import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockJwtAuth;
@WebMvcTest(controllers = GreetingController.class, properties = { "server.ssl.enabled=false" })
class SpringAddonsGreetingControllerUnitTest {
@MockBean
MessageService messageService;
@Autowired
MockMvc api;
/*-----------------------------------------------------------------------------*/
/* /greet */
/* This end-point secured with ".anyRequest().authenticated()" in SecurityConf */
/*-----------------------------------------------------------------------------*/
@Test
@WithAnonymousUser
void givenUserIsNotAuthenticated_whenGetGreet_thenUnauthorized() throws Exception {
// @formatter:off
api.perform(get("/greet"))
.andExpect(status().isUnauthorized());
// @formatter:on
}
@Test
@WithMockJwtAuth
void givenUserIsAuthenticated_whenGetGreet_thenOk() throws Exception {
final var greeting = "Whatever the service returns";
when(messageService.greet()).thenReturn(greeting);
// @formatter:off
api.perform(get("/greet"))
.andExpect(status().isOk())
.andExpect(content().string(greeting));
// @formatter:on
verify(messageService, times(1)).greet();
}
/*---------------------------------------------------------------------------------------------------------------------*/
/* /secured-route */
/* This end-point is secured with ".requestMatchers("/secured-route").hasRole("AUTHORIZED_PERSONNEL")" in SecurityConf */
/*---------------------------------------------------------------------------------------------------------------------*/
@Test
@WithAnonymousUser
void givenUserIsNotAuthenticated_whenGetSecuredRoute_thenUnauthorized() throws Exception {
// @formatter:off
api.perform(get("/secured-route"))
.andExpect(status().isUnauthorized());
// @formatter:on
}
@Test
@WithMockJwtAuth({ "admin", "ROLE_AUTHORIZED_PERSONNEL" })
void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception {
final var secret = "Secret!";
when(messageService.getSecret()).thenReturn(secret);
// @formatter:off
api.perform(get("/secured-route"))
.andExpect(status().isOk())
.andExpect(content().string(secret));
// @formatter:on
}
@Test
@WithMockJwtAuth({ "admin" })
void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() throws Exception {
// @formatter:off
api.perform(get("/secured-route"))
.andExpect(status().isForbidden());
// @formatter:on
}
/*---------------------------------------------------------------------------------------------------------*/
/* /secured-method */
/* This end-point is secured with "@PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')")" on @Controller method */
/*---------------------------------------------------------------------------------------------------------*/
@Test
@WithAnonymousUser
void givenUserIsNotAuthenticated_whenGetSecuredMethod_thenUnauthorized() throws Exception {
// @formatter:off
api.perform(get("/secured-method"))
.andExpect(status().isUnauthorized());
// @formatter:on
}
@Test
@WithMockJwtAuth({ "admin", "ROLE_AUTHORIZED_PERSONNEL" })
void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception {
final var secret = "Secret!";
when(messageService.getSecret()).thenReturn(secret);
// @formatter:off
api.perform(get("/secured-method"))
.andExpect(status().isOk())
.andExpect(content().string(secret));
// @formatter:on
}
@Test
@WithMockJwtAuth(authorities = { "admin" })
void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() throws Exception {
// @formatter:off
api.perform(get("/secured-method"))
.andExpect(status().isForbidden());
// @formatter:on
}
}

View File

@@ -0,0 +1,124 @@
package com.baeldung;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.anonymous;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt;
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.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.test.web.servlet.MockMvc;
import com.baeldung.ServletResourceServerApplication.GreetingController;
import com.baeldung.ServletResourceServerApplication.MessageService;
@WebMvcTest(controllers = GreetingController.class, properties = { "server.ssl.enabled=false" })
class SpringSecurityTestGreetingControllerUnitTest {
@MockBean
MessageService messageService;
@Autowired
MockMvc api;
/*-----------------------------------------------------------------------------*/
/* /greet */
/* This end-point secured with ".anyRequest().authenticated()" in SecurityConf */
/*-----------------------------------------------------------------------------*/
@Test
void givenUserIsNotAuthenticated_whenGetGreet_thenUnauthorized() throws Exception {
// @formatter:off
api.perform(get("/greet").with(anonymous()))
.andExpect(status().isUnauthorized());
// @formatter:on
}
@Test
void givenUserIsAuthenticated_whenGetGreet_thenOk() throws Exception {
final var greeting = "Whatever the service returns";
when(messageService.greet()).thenReturn(greeting);
// @formatter:off
api.perform(get("/greet").with(jwt()))
.andExpect(status().isOk())
.andExpect(content().string(greeting));
// @formatter:on
verify(messageService, times(1)).greet();
}
/*---------------------------------------------------------------------------------------------------------------------*/
/* /secured-route */
/* This end-point is secured with ".requestMatchers("/secured-route").hasRole("AUTHORIZED_PERSONNEL")" in SecurityConf */
/*---------------------------------------------------------------------------------------------------------------------*/
@Test
void givenUserIsNotAuthenticated_whenGetSecuredRoute_thenUnauthorized() throws Exception {
// @formatter:off
api.perform(get("/secured-route").with(anonymous()))
.andExpect(status().isUnauthorized());
// @formatter:on
}
@Test
void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception {
final var secret = "Secret!";
when(messageService.getSecret()).thenReturn(secret);
// @formatter:off
api.perform(get("/secured-route").with(jwt().authorities(new SimpleGrantedAuthority("ROLE_AUTHORIZED_PERSONNEL"))))
.andExpect(status().isOk())
.andExpect(content().string(secret));
// @formatter:on
}
@Test
void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() throws Exception {
// @formatter:off
api.perform(get("/secured-route").with(jwt().authorities(new SimpleGrantedAuthority("admin"))))
.andExpect(status().isForbidden());
// @formatter:on
}
/*---------------------------------------------------------------------------------------------------------*/
/* /secured-method */
/* This end-point is secured with "@PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')")" on @Controller method */
/*---------------------------------------------------------------------------------------------------------*/
@Test
void givenUserIsNotAuthenticated_whenGetSecuredMethod_thenUnauthorized() throws Exception {
// @formatter:off
api.perform(get("/secured-method").with(anonymous()))
.andExpect(status().isUnauthorized());
// @formatter:on
}
@Test
void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception {
final var secret = "Secret!";
when(messageService.getSecret()).thenReturn(secret);
// @formatter:off
api.perform(get("/secured-method").with(jwt().authorities(new SimpleGrantedAuthority("ROLE_AUTHORIZED_PERSONNEL"))))
.andExpect(status().isOk())
.andExpect(content().string(secret));
// @formatter:on
}
@Test
void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() throws Exception {
// @formatter:off
api.perform(get("/secured-method").with(jwt().authorities(new SimpleGrantedAuthority("admin"))))
.andExpect(status().isForbidden());
// @formatter:on
}
}