diff --git a/src/main/java/djmil/cashcard/SecurityConfig.java b/src/main/java/djmil/cashcard/SecurityConfig.java index ec6c028..766d87a 100644 --- a/src/main/java/djmil/cashcard/SecurityConfig.java +++ b/src/main/java/djmil/cashcard/SecurityConfig.java @@ -18,7 +18,8 @@ public class SecurityConfig { public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests() .requestMatchers("/cashcards/**") - .authenticated() + //.authenticated() + .hasRole("CARD-OWNER") // <<-- enable RBAC .and() .csrf().disable() .httpBasic(); @@ -34,11 +35,19 @@ public class SecurityConfig { @Bean public UserDetailsService testOnlyUsers(PasswordEncoder passwordEncoder) { User.UserBuilder users = User.builder(); + UserDetails sarah = users .username("sarah1") .password(passwordEncoder.encode("abc123")) - .roles() // No roles for now + .roles("CARD-OWNER") // new role .build(); - return new InMemoryUserDetailsManager(sarah); + + UserDetails hankOwnsNoCards = users + .username("hank-owns-no-cards") + .password(passwordEncoder.encode("qrs456")) + .roles("NON-OWNER") // new role + .build(); + + return new InMemoryUserDetailsManager(sarah, hankOwnsNoCards); } } \ No newline at end of file diff --git a/src/test/java/djmil/cashcard/CashcardApplicationTests.java b/src/test/java/djmil/cashcard/CashcardApplicationTests.java index 8a004a2..a17ef59 100644 --- a/src/test/java/djmil/cashcard/CashcardApplicationTests.java +++ b/src/test/java/djmil/cashcard/CashcardApplicationTests.java @@ -66,7 +66,6 @@ class CashcardApplicationTests { assertThat(createResponse.getStatusCode()).isEqualTo(HttpStatus.CREATED); - // Validate created CashCard URI locationOfNewCashCard = createResponse.getHeaders().getLocation(); ResponseEntity getResponse = restTemplate @@ -154,4 +153,12 @@ class CashcardApplicationTests { .getForEntity("/cashcards/99", String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } + + @Test + void shouldRejectUsersWhoAreNotCardOwners() { + ResponseEntity response = restTemplate + .withBasicAuth("hank-owns-no-cards", "qrs456") + .getForEntity("/cashcards/99", String.class); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); + } }