Baeldung source format

This commit is contained in:
ch4mpy
2023-02-25 14:36:42 -10:00
parent 66d71f0697
commit 26e401b290
13 changed files with 384 additions and 375 deletions
@@ -44,18 +44,25 @@ public class ServletResourceServerApplication {
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.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
.requestMatchers("/secured-route")
.hasRole("AUTHORIZED_PERSONNEL")
.anyRequest()
.authenticated();
return http.build();
}
@@ -66,10 +73,14 @@ public class ServletResourceServerApplication {
@Bean
AuthoritiesConverter realmRoles2AuthoritiesConverter() {
return (Jwt jwt) -> {
final var realmRoles = Optional.of(jwt.getClaimAsMap("realm_access")).orElse(Map.of());
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();
return roles.stream()
.map(SimpleGrantedAuthority::new)
.map(GrantedAuthority.class::cast)
.toList();
};
}
}
@@ -78,11 +89,10 @@ public class ServletResourceServerApplication {
public static class MessageService {
public String greet() {
final var who = (JwtAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
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());
return "Hello %s! You are granted with %s.".formatted(claims.getOrDefault(StandardClaimNames.PREFERRED_USERNAME, claims.get(StandardClaimNames.SUB)), who.getAuthorities());
}
@PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')")
@@ -29,22 +29,16 @@ class ServletResourceServerApplicationIntegrationTest {
@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"))
@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
.andExpect(status().isOk())
.andExpect(content().string("Hello ch4mpy! You are granted with [admin, ROLE_AUTHORIZED_PERSONNEL]."));
}
/*---------------------------------------------------------------------------------------------------------------------*/
@@ -55,31 +49,25 @@ class ServletResourceServerApplicationIntegrationTest {
@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
.andExpect(status().isOk())
.andExpect(content().string("Only authorized personnel can read that"));
}
@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 */
@@ -88,29 +76,23 @@ class ServletResourceServerApplicationIntegrationTest {
@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
}
}
@@ -36,25 +36,19 @@ class SpringAddonsGreetingControllerUnitTest {
@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"))
@WithMockJwtAuth(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy"))
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();
}
@@ -67,10 +61,8 @@ class SpringAddonsGreetingControllerUnitTest {
@Test
@WithAnonymousUser
void givenUserIsNotAuthenticated_whenGetSecuredRoute_thenUnauthorized() throws Exception {
// @formatter:off
api.perform(get("/secured-route"))
.andExpect(status().isUnauthorized());
// @formatter:on
}
@Test
@@ -79,22 +71,18 @@ class SpringAddonsGreetingControllerUnitTest {
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 */
@@ -103,10 +91,8 @@ class SpringAddonsGreetingControllerUnitTest {
@Test
@WithAnonymousUser
void givenUserIsNotAuthenticated_whenGetSecuredMethod_thenUnauthorized() throws Exception {
// @formatter:off
api.perform(get("/secured-method"))
.andExpect(status().isUnauthorized());
// @formatter:on
}
@Test
@@ -115,20 +101,16 @@ class SpringAddonsGreetingControllerUnitTest {
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
}
}
@@ -38,10 +38,8 @@ class SpringSecurityTestGreetingControllerUnitTest {
@Test
void givenUserIsNotAuthenticated_whenGetGreet_thenUnauthorized() throws Exception {
// @formatter:off
api.perform(get("/greet").with(anonymous()))
.andExpect(status().isUnauthorized());
// @formatter:on
}
@Test
@@ -49,13 +47,10 @@ class SpringSecurityTestGreetingControllerUnitTest {
final var greeting = "Whatever the service returns";
when(messageService.greet()).thenReturn(greeting);
// @formatter:off
api.perform(get("/greet").with(jwt()
.authorities(List.of(new SimpleGrantedAuthority("admin"), new SimpleGrantedAuthority("ROLE_AUTHORIZED_PERSONNEL")))
.jwt(jwt -> jwt.claim(StandardClaimNames.PREFERRED_USERNAME, "ch4mpy"))))
api.perform(get("/greet").with(jwt().authorities(List.of(new SimpleGrantedAuthority("admin"), new SimpleGrantedAuthority("ROLE_AUTHORIZED_PERSONNEL")))
.jwt(jwt -> jwt.claim(StandardClaimNames.PREFERRED_USERNAME, "ch4mpy"))))
.andExpect(status().isOk())
.andExpect(content().string(greeting));
// @formatter:on
verify(messageService, times(1)).greet();
}
@@ -67,10 +62,8 @@ class SpringSecurityTestGreetingControllerUnitTest {
@Test
void givenUserIsNotAuthenticated_whenGetSecuredRoute_thenUnauthorized() throws Exception {
// @formatter:off
api.perform(get("/secured-route").with(anonymous()))
.andExpect(status().isUnauthorized());
// @formatter:on
}
@Test
@@ -78,21 +71,17 @@ class SpringSecurityTestGreetingControllerUnitTest {
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 */
@@ -100,10 +89,8 @@ class SpringSecurityTestGreetingControllerUnitTest {
@Test
void givenUserIsNotAuthenticated_whenGetSecuredMethod_thenUnauthorized() throws Exception {
// @formatter:off
api.perform(get("/secured-method").with(anonymous()))
.andExpect(status().isUnauthorized());
// @formatter:on
}
@Test
@@ -111,19 +98,15 @@ class SpringSecurityTestGreetingControllerUnitTest {
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
}
}