SpringSecurity: Authorization
This commit is contained in:
parent
30aff2259e
commit
f4b171add1
@ -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);
|
||||
}
|
||||
}
|
@ -66,7 +66,6 @@ class CashcardApplicationTests {
|
||||
|
||||
assertThat(createResponse.getStatusCode()).isEqualTo(HttpStatus.CREATED);
|
||||
|
||||
|
||||
// Validate created CashCard
|
||||
URI locationOfNewCashCard = createResponse.getHeaders().getLocation();
|
||||
ResponseEntity<String> getResponse = restTemplate
|
||||
@ -154,4 +153,12 @@ class CashcardApplicationTests {
|
||||
.getForEntity("/cashcards/99", String.class);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user