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

Method Security

Rules on methods.

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

URL rules are great, but sometimes the rule depends on the data. Like, you may only see your own profile. For that, we put rules on methods.

  • URL rules
  • Rules about data
  • Rules on methods

@PreAuthorize

At Enable Method Security turns method rules on. At Pre Authorize runs a check, before the method. Refund all needs the admin role. And profile compares the name parameter, with the logged in user's name.

SecurityConfig.java · AccountService.javajava
@Configuration
@EnableMethodSecurity
...

@Service
public class AccountService {

    @PreAuthorize("hasRole('ADMIN')")
    public String refundAll() {
        return "All orders refunded";
    }

    @PreAuthorize("#name == authentication.name")
    public String profile(String name) {
        return "Profile of " + name;
    }
}

Rules that read the data

The controller just calls the service. The rules live on the service methods. Run it. Sam can't refund, so it's four oh three. Alex can. Sam can see Sam's own profile. But Sam can't see Alex's profile.

AccountService.javajava
@Service
public class AccountService {

    @PreAuthorize("hasRole('ADMIN')")
    public String refundAll() {
        return "All orders refunded";
    }

    @PreAuthorize("#name == authentication.name")
    public String profile(String name) {
        return "Profile of " + name;
    }
}
Output
$ curl -i -u sam:reader1 -X POST localhost:8080/refunds | head -1
HTTP/1.1 403
$ curl -u alex:boss123 -X POST localhost:8080/refunds
All orders refunded
$ curl -u sam:reader1 localhost:8080/profiles/sam
Profile of sam
$ curl -i -u sam:reader1 localhost:8080/profiles/alex | head -1
HTTP/1.1 403
Also uses SecurityConfig.java
@Configuration
@EnableMethodSecurity
public class SecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
            .httpBasic(Customizer.withDefaults()).csrf(csrf -> csrf.disable());
        return http.build();
    }
}
Also uses AccountController.java
@RestController
public class AccountController {
    private final AccountService accounts;
    public AccountController(AccountService accounts) { this.accounts = accounts; }

    @PostMapping("/refunds")
    public String refund() { return accounts.refundAll(); }

    @GetMapping("/profiles/{name}")
    public String profile(@PathVariable String name) { return accounts.profile(name); }
}
Also uses UserConfig.java
@Configuration
public class UserConfig {
    @Bean
    UserDetailsService users() {
        return new InMemoryUserDetailsManager(
            User.withUsername("sam").password("{noop}reader1").roles("USER").build(),
            User.withUsername("alex").password("{noop}boss123").roles("USER", "ADMIN").build());
    }
}
Also uses _curl.sh
curl -i -u sam:reader1 -X POST localhost:8080/refunds | head -1
curl -u alex:boss123 -X POST localhost:8080/refunds
curl -u sam:reader1 localhost:8080/profiles/sam
curl -i -u sam:reader1 localhost:8080/profiles/alex | head -1
Also uses _profile
security

URL rules or method rules?

Use URL rules for broad areas, like public, and admin. Use method rules for rules about data, like owners. Method rules protect the service, no matter which controller calls it. Most apps use both.

keyvalue
URL rulesbroad areas
Method rulesrules about data
Bonusprotects every caller
Most appsuse both

Summary

At Enable Method Security, and at Pre Authorize, put security rules on service methods, even rules that read the parameters. Next, some practice.

Key takeaways
  • @EnableMethodSecurity
  • @PreAuthorize
  • #name == authentication.name
Next up: Practice: A Secured API — your turn