SpringSecurity: Authorization

This commit is contained in:
djmil 2023-07-24 13:37:04 +02:00
parent 30aff2259e
commit f4b171add1
2 changed files with 20 additions and 4 deletions

View File

@ -18,7 +18,8 @@ public class SecurityConfig {
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests() http.authorizeHttpRequests()
.requestMatchers("/cashcards/**") .requestMatchers("/cashcards/**")
.authenticated() //.authenticated()
.hasRole("CARD-OWNER") // <<-- enable RBAC
.and() .and()
.csrf().disable() .csrf().disable()
.httpBasic(); .httpBasic();
@ -34,11 +35,19 @@ public class SecurityConfig {
@Bean @Bean
public UserDetailsService testOnlyUsers(PasswordEncoder passwordEncoder) { public UserDetailsService testOnlyUsers(PasswordEncoder passwordEncoder) {
User.UserBuilder users = User.builder(); User.UserBuilder users = User.builder();
UserDetails sarah = users UserDetails sarah = users
.username("sarah1") .username("sarah1")
.password(passwordEncoder.encode("abc123")) .password(passwordEncoder.encode("abc123"))
.roles() // No roles for now .roles("CARD-OWNER") // new role
.build(); .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);
} }
} }

View File

@ -66,7 +66,6 @@ class CashcardApplicationTests {
assertThat(createResponse.getStatusCode()).isEqualTo(HttpStatus.CREATED); assertThat(createResponse.getStatusCode()).isEqualTo(HttpStatus.CREATED);
// Validate created CashCard // Validate created CashCard
URI locationOfNewCashCard = createResponse.getHeaders().getLocation(); URI locationOfNewCashCard = createResponse.getHeaders().getLocation();
ResponseEntity<String> getResponse = restTemplate ResponseEntity<String> getResponse = restTemplate
@ -154,4 +153,12 @@ class CashcardApplicationTests {
.getForEntity("/cashcards/99", String.class); .getForEntity("/cashcards/99", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
} }
@Test
void shouldRejectUsersWhoAreNotCardOwners() {
ResponseEntity<String> response = restTemplate
.withBasicAuth("hank-owns-no-cards", "qrs456")
.getForEntity("/cashcards/99", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
}
} }