Skip to content

Commit

Permalink
Add test when user does not have the proper role for an endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
wimdeblauwe committed Apr 24, 2024
1 parent 0d373d1 commit 6f8cdab
Showing 1 changed file with 21 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.web.SecurityFilterChain;
Expand Down Expand Up @@ -43,6 +45,16 @@ void testUnauthorized() throws Exception {
.andExpect(jsonPath("message").value("Full authentication is required to access this resource"));
}

@Test
@WithMockUser
void testForbidden() throws Exception {
mockMvc.perform(get("/test/spring-security/admin"))
.andExpect(status().isForbidden())
.andExpect(header().string("Content-Type", "application/json"))
.andExpect(jsonPath("code").value("ACCESS_DENIED"))
.andExpect(jsonPath("message").value("Access Denied"));
}

@Test
@WithMockUser
void testAccessDenied() throws Exception {
Expand Down Expand Up @@ -76,9 +88,16 @@ public void throwAccessDenied() {
public void throwAccountExpired() {
throw new AccountExpiredException("Fake account expired");
}

@GetMapping("/admin")
@Secured("ADMIN")
public void requiresAdminRole() {

}
}

@TestConfiguration
@EnableMethodSecurity(securedEnabled = true)
static class TestConfig {
@Bean
public UnauthorizedEntryPoint unauthorizedEntryPoint(HttpStatusMapper httpStatusMapper, ErrorCodeMapper errorCodeMapper, ErrorMessageMapper errorMessageMapper, ObjectMapper objectMapper) {
Expand All @@ -92,7 +111,8 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http,

http.authorizeHttpRequests().anyRequest().authenticated();

http.exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint);
http.exceptionHandling()
.authenticationEntryPoint(unauthorizedEntryPoint);

return http.build();
}
Expand Down

0 comments on commit 6f8cdab

Please sign in to comment.