SpringSecurity: Authorisation and Roles

This commit is contained in:
djmil 2023-07-24 14:19:41 +02:00
parent f4b171add1
commit d3751dda0f
4 changed files with 32 additions and 9 deletions

View File

@ -13,6 +13,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.UriComponentsBuilder;
import java.security.Principal;
import java.net.URI; import java.net.URI;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@ -28,8 +30,12 @@ public class CashCardController {
} }
@GetMapping("/{requestedId}") @GetMapping("/{requestedId}")
public ResponseEntity<CashCard> findById(@PathVariable Long requestedId) { public ResponseEntity<CashCard> findById(@PathVariable Long requestedId, Principal principal) {
Optional<CashCard> cashCardOptional = cashCardRepository.findById(requestedId); CashCard cashCard = cashCardRepository.findByIdAndOwner(
requestedId,
principal.getName()
);
Optional<CashCard> cashCardOptional = Optional.ofNullable(cashCard);
if (cashCardOptional.isPresent()) { if (cashCardOptional.isPresent()) {
return ResponseEntity.ok(cashCardOptional.get()); return ResponseEntity.ok(cashCardOptional.get());
@ -44,8 +50,9 @@ public class CashCardController {
// } // }
@GetMapping @GetMapping
public ResponseEntity<List<CashCard>> findAll(Pageable pageable) { public ResponseEntity<List<CashCard>> findAll(Pageable pageable, Principal principal) {
Page<CashCard> page = cashCardRepository.findAll( Page<CashCard> page = cashCardRepository.findByOwner(
principal.getName(),
PageRequest.of( PageRequest.of(
pageable.getPageNumber(), pageable.getPageNumber(),
pageable.getPageSize(), pageable.getPageSize(),
@ -56,13 +63,15 @@ public class CashCardController {
} }
@PostMapping @PostMapping
private ResponseEntity<Void> createCashCard(@RequestBody CashCard newCashCardRequest, UriComponentsBuilder ucb) { private ResponseEntity<Void> createCashCard(@RequestBody CashCard newCashCardRequest, UriComponentsBuilder ucb, Principal principal) {
CashCard savedCashCard = cashCardRepository.save(newCashCardRequest); // CRUD - Create CashCard cashCardWithOwner = new CashCard(null, newCashCardRequest.amount(), principal.getName());
CashCard savedCashCard = cashCardRepository.save(cashCardWithOwner); // CRUD - Create
URI locationOfNewCashCard = ucb URI locationOfNewCashCard = ucb
.path("cashcards/{id}") .path("cashcards/{id}")
.buildAndExpand(savedCashCard.id()) .buildAndExpand(savedCashCard.id())
.toUri(); .toUri();
return ResponseEntity.created(locationOfNewCashCard).build(); return ResponseEntity.created(locationOfNewCashCard).build();
} }
} }

View File

@ -2,10 +2,15 @@ package djmil.cashcard;
import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
public interface public interface
CashCardRepository CashCardRepository
extends extends
CrudRepository<CashCard, Long>, CrudRepository<CashCard, Long>,
PagingAndSortingRepository<CashCard, Long> { PagingAndSortingRepository<CashCard, Long>
{
CashCard findByIdAndOwner(Long id, String owner);
Page<CashCard> findByOwner(String owner, PageRequest amount);
} }

View File

@ -59,7 +59,7 @@ class CashcardApplicationTests {
@Test @Test
@DirtiesContext @DirtiesContext
void shouldCreateANewCashCard() { void shouldCreateANewCashCard() {
CashCard newCashCard = new CashCard(null, 250.00, "sarah1"); CashCard newCashCard = new CashCard(null, 250.00, null);
ResponseEntity<Void> createResponse = restTemplate ResponseEntity<Void> createResponse = restTemplate
.withBasicAuth("sarah1", "abc123") .withBasicAuth("sarah1", "abc123")
.postForEntity("/cashcards", newCashCard, Void.class ); .postForEntity("/cashcards", newCashCard, Void.class );
@ -161,4 +161,12 @@ class CashcardApplicationTests {
.getForEntity("/cashcards/99", String.class); .getForEntity("/cashcards/99", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
} }
@Test
void shouldNotAllowAccessToCashCardsTheyDoNotOwn() {
ResponseEntity<String> response = restTemplate
.withBasicAuth("sarah1", "abc123")
.getForEntity("/cashcards/102", String.class); // <<-- kumar2's data
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
}
} }

View File

@ -1,3 +1,4 @@
INSERT INTO CASH_CARD(ID, AMOUNT, OWNER) VALUES (99, 123.45, 'sarah1'); INSERT INTO CASH_CARD(ID, AMOUNT, OWNER) VALUES (99, 123.45, 'sarah1');
INSERT INTO CASH_CARD(ID, AMOUNT, OWNER) VALUES (100, 1.00, 'sarah1'); INSERT INTO CASH_CARD(ID, AMOUNT, OWNER) VALUES (100, 1.00, 'sarah1');
INSERT INTO CASH_CARD(ID, AMOUNT, OWNER) VALUES (101, 150.00, 'sarah1'); INSERT INTO CASH_CARD(ID, AMOUNT, OWNER) VALUES (101, 150.00, 'sarah1');
INSERT INTO CASH_CARD(ID, AMOUNT, OWNER) VALUES (102, 200.00, 'kumar2');