AI Hints
Home›Spring Boot Tutorial›Protecting Endpoints by Role, Method Security and Practice: A Secured API
Spring Boot · Lesson 99 of 120

Practice: A Secured API

Your turn.

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

Let's practise security. The controller has three endpoints. You'll write the rules.

  • Three endpoints
  • Write the rules
  • Your turn

The controller

GET lists books. POST adds one. And DELETE removes one.

BookController.javajava
@RestController
public class BookController {

    @GetMapping("/books")
    public String list() { return "Book list"; }

    @PostMapping("/books")
    public String add() { return "Book added"; }

    @DeleteMapping("/books/{id}")
    public String delete(@PathVariable int id) { return "Book " + id + " deleted"; }
}

The security rules

Your turn. Pause the video, and try this. Anyone may list books. Users, and admins, may add books. Only admins may delete. Here is one solution. The rules use the HTTP method, and the path. Anyone lists. A visitor can't add, so it's four oh one. Sam can add. Sam can't delete, so it's four oh three. And Alex can.

✍️ Exercise: The security rules

SecurityFilterChain: GET /books → everyone; POST /books → USER or ADMIN; DELETE /books/** → ADMIN only.

Show hint

requestMatchers(HttpMethod.POST, "/books").hasAnyRole("USER", "ADMIN")

Show solution
SecurityConfig.javajava
@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth
                .requestMatchers(HttpMethod.GET, "/books/**").permitAll()
                .requestMatchers(HttpMethod.POST, "/books").hasAnyRole("USER", "ADMIN")
                .requestMatchers(HttpMethod.DELETE, "/books/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .httpBasic(Customizer.withDefaults()).csrf(csrf -> csrf.disable());
        return http.build();
    }
}
Output
$ curl localhost:8080/books
Book list
$ curl -i -X POST localhost:8080/books | head -1
HTTP/1.1 401
$ curl -u sam:reader1 -X POST localhost:8080/books
Book added
$ curl -i -u sam:reader1 -X DELETE localhost:8080/books/2 | head -1
HTTP/1.1 403
$ curl -u alex:boss123 -X DELETE localhost:8080/books/2
Book 2 deleted

What module eleven taught

Spring Security locks everything by default. A Security Filter Chain sets the rules. A User Details Service loads users, with BCrypt hashed passwords. Roles control what users may do. And at Pre Authorize protects methods.

keyvalue
Defaulteverything locked
RulesSecurityFilterChain
UsersUserDetailsService + BCrypt
RoleshasRole, @PreAuthorize

Summary

Your API now knows who's calling, and what they may do. That's the end of module eleven. Next module, testing.

Key takeaways
  • Authentication
  • Roles
  • Method security
Next up: Why Test — confidence to change code