Spring Boot Tutorial 120 lessons · 2:38:34+ of video
Spring Boot Home What Spring Boot Is, Where Spring Boot Is Used and How a Web App Works
What Spring Boot Is Where Spring Boot Is Used How a Web App Works What You Need, Spring Initializr and The Project Structure
What You Need Spring Initializr The Project Structure The Main Class, Running the App and Your First Endpoint
The Main Class Running the App Your First Endpoint HTTP Methods, Status Codes and JSON
HTTP Methods Status Codes JSON Testing with curl, @RestController and @GetMapping
Testing with curl @RestController @GetMapping Path Variables, Query Parameters and Practice: A Greeting API
Path Variables Query Parameters Practice: A Greeting API What REST Is, Returning Objects as JSON and Records for Data
What REST Is Returning Objects as JSON Records for Data @PostMapping and @RequestBody, @PutMapping and @DeleteMapping
@PostMapping and @RequestBody @PutMapping @DeleteMapping ResponseEntity, Status Codes in Practice and Practice: A Book API in Memory
ResponseEntity Status Codes in Practice Practice: A Book API in Memory Inversion of Control, Beans and Dependency Injection
Inversion of Control Beans Dependency Injection @Service, Constructor Injection and @Component and Friends
@Service Constructor Injection @Component and Friends @Configuration and @Bean, Bean Scopes and Practice: Layers
@Configuration and @Bean Bean Scopes Practice: Layers application.properties, @Value and @ConfigurationProperties
application.properties @Value @ConfigurationProperties YAML, Profiles and Logging
YAML Profiles Logging CommandLineRunner, Environment Variables and Practice: A Configurable Shop
CommandLineRunner Environment Variables Practice: A Configurable Shop Why a Database, The H2 Database and What JPA Is
Why a Database The H2 Database What JPA Is Entities, Ids and Generated Values and Repositories
Entities Ids and Generated Values Repositories CRUD with JpaRepository, Seeding Data and Practice: Books in a Database
CRUD with JpaRepository Seeding Data Practice: Books in a Database Derived Query Methods, More Query Keywords and Sorting
Derived Query Methods More Query Keywords Sorting Paging, @Query with JPQL and Native Queries
Paging @Query with JPQL Native Queries Counting and Exists, Transactions and Practice: Search Books
Counting and Exists Transactions Practice: Search Books Relationships, @ManyToOne and @OneToMany
Relationships @ManyToOne @OneToMany Lazy Loading, Cascade and Many to Many
Lazy Loading Cascade Many to Many DTOs for Relationships, Avoiding Endless JSON and Practice: Authors and Books
DTOs for Relationships Avoiding Endless JSON Practice: Authors and Books Why Validate, Bean Validation and @Valid
Why Validate Bean Validation @Valid Validation Errors, Custom Exceptions and @ResponseStatus
Validation Errors Custom Exceptions @ResponseStatus @RestControllerAdvice, ProblemDetail and Practice: Clean Errors
@RestControllerAdvice ProblemDetail Practice: Clean Errors Controller, Service, Repository, Mapping Entities to DTOs and Update Requests
Controller, Service, Repository Mapping Entities to DTOs Update Requests PATCH, Filtering with Query Parameters and Pagination in the API
PATCH Filtering with Query Parameters Pagination in the API API Versioning, CORS and Practice: A Complete Books API
API Versioning CORS Practice: A Complete Books API Spring Security Basics, Locked by Default and SecurityFilterChain
Spring Security Basics Locked by Default SecurityFilterChain Users and Passwords, Password Encoding and Roles
Users and Passwords Password Encoding Roles Protecting Endpoints by Role, Method Security and Practice: A Secured API
Protecting Endpoints by Role Method Security Practice: A Secured API Why Test, JUnit Basics and Testing a Service
Why Test JUnit Basics Testing a Service Mockito, @WebMvcTest and MockMvc
Mockito @WebMvcTest MockMvc @DataJpaTest, @SpringBootTest and Practice: Test the API
@DataJpaTest @SpringBootTest Practice: Test the API Actuator, Health and Info and Packaging a Jar
Actuator Health and Info Packaging a Jar Project: The Plan, Entities, Repositories and Service
Project: The Plan Project: Entities Project: Repositories and Service Project: The Controller, Validation and Errors and Security
Project: The Controller Project: Validation and Errors Project: Security Project: Tests, Where to Go Next and Course Recap
Project: Tests Where to Go Next Course Recap Spring Boot · Lesson 98 of 120
Method Security Rules on methods.
⏱ 2 min read ▶ Video at 2:09:41 🎓 Free
▶ starts at 2:09:41 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 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.java java Copy
@ 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;
}
} 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.java java Copy
@ 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 Prefer to watch? The full Spring Boot course is free All lessons in one video with animations, real code and chapters.
Watch free 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.
key value URL rules broad areas Method rules rules about data Bonus protects every caller Most apps use both
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