AI Hints
Home›Spring Boot Tutorial›Project: The Controller, Validation and Errors and Security
Spring Boot · Lesson 117 of 120

Project: Security

Who may do what.

⏱ 2 min read▶ Video at 2:35:33🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

Right now, anyone can delete our books. Let's add security, using the rules we planned.

  • Anyone can delete
  • Add security
  • Follow the plan

UserConfig.java

A BCrypt encoder hashes the passwords. Sam is a normal user. And Alex is a user, and an admin.

UserConfig.javajava
@Configuration
public class UserConfig {

    @Bean
    PasswordEncoder encoder() { return new BCryptPasswordEncoder(); }

    @Bean
    UserDetailsService users(PasswordEncoder encoder) {
        return new InMemoryUserDetailsManager(
            User.withUsername("sam").password(encoder.encode("reader1"))
                .roles("USER").build(),
            User.withUsername("alex").password(encoder.encode("boss123"))
                .roles("USER", "ADMIN").build());
    }
}

SecurityConfig.java

GET requests on books are open to everyone. DELETE needs the admin role. Every other request needs a user, or an admin. HTTP Basic carries the login, and CSRF is off, for this API. Run it. Anyone can read book one. A visitor can't add a book, so it's four oh one. Sam can add one. Sam can't delete, so it's four oh three. And Alex, the admin, can.

SecurityConfig.javajava
@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth
                .requestMatchers(HttpMethod.GET, "/books/**").permitAll()
                .requestMatchers(HttpMethod.DELETE, "/books/**").hasRole("ADMIN")
                .anyRequest().hasAnyRole("USER", "ADMIN"))
            .httpBasic(Customizer.withDefaults()).csrf(csrf -> csrf.disable());
        return http.build();
    }
}
Output
$ curl localhost:8080/books/1
{"id":1,"title":"Dune","author":"Frank Herbert","price":9.99}
$ curl -i --json "$BOOK" localhost:8080/books | head -1
HTTP/1.1 401
$ curl -u sam:reader1 --json "$BOOK" localhost:8080/books
{"id":9,"title":"Beloved","author":"Toni Morrison","price":9.5}
$ curl -i -u sam:reader1 -X DELETE localhost:8080/books/1 | head -1
HTTP/1.1 403
$ curl -i -u alex:boss123 -X DELETE localhost:8080/books/1 | head -1
HTTP/1.1 204
Also uses Book.java
@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String author;
    private double price;

    protected Book() {}
    public Book(String title, String author, double price) {
        this.title = title; this.author = author; this.price = price;
    }
    public Long getId() { return id; }
    public String getTitle() { return title; }
    public String getAuthor() { return author; }
    public double getPrice() { return price; }
    public void setTitle(String title) { this.title = title; }
    public void setAuthor(String author) { this.author = author; }
    public void setPrice(double price) { this.price = price; }
}
Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {

    List<Book> findByAuthorContainingIgnoreCase(String author);
}
Also uses CreateBook.java
public record CreateBook(
    @NotBlank String title,
    @NotBlank String author,
    @Positive double price
) {}
Also uses BookResponse.java
public record BookResponse(Long id, String title, String author, double price) {

    static BookResponse from(Book b) {
        return new BookResponse(b.getId(), b.getTitle(), b.getAuthor(), b.getPrice());
    }
}
Also uses NewPrice.java
public record NewPrice(@Positive double price) {}
Also uses BookNotFoundException.java
@ResponseStatus(HttpStatus.NOT_FOUND)
public class BookNotFoundException extends RuntimeException {
    public BookNotFoundException(long id) { super("Book " + id + " was not found"); }
}
Also uses data.sql
INSERT INTO book (title, author, price) VALUES
  ('Dune', 'Frank Herbert', 9.99),
  ('The Hobbit', 'J.R.R. Tolkien', 8.99),
  ('Circe', 'Madeline Miller', 10.99),
  ('Children of Dune', 'Frank Herbert', 8.49),
  ('Song of Achilles', 'Madeline Miller', 9.49),
  ('The Fellowship of the Ring', 'J.R.R. Tolkien', 11.99),
  ('Emma', 'Jane Austen', 6.99),
  ('Persuasion', 'Jane Austen', 7.49);
Also uses application.properties
spring.jpa.defer-datasource-initialization=true
Also uses BookService.java
@Service
@Transactional
public class BookService {

    private final BookRepository books;

    public BookService(BookRepository books) { this.books = books; }

    @Transactional(readOnly = true)
    public List<BookResponse> search(String author) {
        List<Book> found = author == null ? books.findAll()
                                          : books.findByAuthorContainingIgnoreCase(author);
        return found.stream().map(BookResponse::from).toList();
    }

    @Transactional(readOnly = true)
    public BookResponse byId(long id) { return BookResponse.from(find(id)); }

    public BookResponse create(CreateBook req) {
        Book saved = books.save(new Book(req.title(), req.author(), req.price()));
        return BookResponse.from(saved);
    }

    public BookResponse changePrice(long id, double price) {
        Book book = find(id);
        book.setPrice(price);
        return BookResponse.from(book);
    }

    public void delete(long id) { books.delete(find(id)); }

    private Book find(long id) {
        return books.findById(id).orElseThrow(() -> new BookNotFoundException(id));
    }
}
Also uses BookController.java
@RestController
@RequestMapping("/books")
public class BookController {

    private final BookService service;
    public BookController(BookService service) { this.service = service; }

    @GetMapping
    public List<BookResponse> list(@RequestParam(required = false) String author) {
        return service.search(author);
    }

    @GetMapping("/{id}")
    public BookResponse one(@PathVariable long id) { return service.byId(id); }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public BookResponse add(@Valid @RequestBody CreateBook req) {
        return service.create(req);
    }

    @PutMapping("/{id}/price")
    public BookResponse price(@PathVariable long id, @Valid @RequestBody NewPrice p) {
        return service.changePrice(id, p.price());
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable long id) { service.delete(id); }
}
Also uses ApiErrors.java
@RestControllerAdvice
public class ApiErrors {

    @ExceptionHandler(BookNotFoundException.class)
    public ProblemDetail notFound(BookNotFoundException ex) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ProblemDetail invalid(MethodArgumentNotValidException ex) {
        var pd = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Invalid input");
        pd.setProperty("errors", ex.getFieldErrors().stream()
                .map(e -> e.getField() + " " + e.getDefaultMessage()).sorted().toList());
        return pd;
    }
}
Also uses UserConfig.java
@Configuration
public class UserConfig {

    @Bean
    PasswordEncoder encoder() { return new BCryptPasswordEncoder(); }

    @Bean
    UserDetailsService users(PasswordEncoder encoder) {
        return new InMemoryUserDetailsManager(
            User.withUsername("sam").password(encoder.encode("reader1"))
                .roles("USER").build(),
            User.withUsername("alex").password(encoder.encode("boss123"))
                .roles("USER", "ADMIN").build());
    }
}
Also uses _curl.sh
BOOK='{"title":"Beloved","author":"Toni Morrison","price":9.5}'
curl localhost:8080/books/1
curl -i --json "$BOOK" localhost:8080/books | head -1
curl -u sam:reader1 --json "$BOOK" localhost:8080/books
curl -i -u sam:reader1 -X DELETE localhost:8080/books/1 | head -1
curl -i -u alex:boss123 -X DELETE localhost:8080/books/1 | head -1
Also uses _profile
security

Summary

Reads are public, users may add and change prices, and only admins may delete. Next, tests for the whole API.

Key takeaways
  • permitAll() for GET
  • hasRole("ADMIN")
  • 401 and 403
Next up: Project: Tests — prove it works