📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
The Basics of Authorization in Spring Security
Authorization determines whether an authenticated entity has the right to access specific resources or perform operations. It's about granting or denying permissions based on roles or policies.Key Components in Authorization
SecurityContextHolder: Stores details of the current security context, including the authenticated user's details and granted authorities.
Expression-Based Access Control: Allows for complex security rules using expressions.
Method Security Annotations: @PreAuthorize, @PostAuthorize, @Secured, etc., for securing methods.
URL-Based Security for REST Endpoints
This code snippet showcases how to set up URL-based authorization in Spring Security, defining specific access controls based on HTTP methods and user roles. This allows for a secure and granular approach to protecting resources and ensuring that only authorized users can perform certain actions within your application.
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable())
.authorizeHttpRequests((authorize) -> {
authorize.requestMatchers(HttpMethod.POST, "/api/**").hasRole("ADMIN");
authorize.requestMatchers(HttpMethod.PUT, "/api/**").hasRole("ADMIN");
authorize.requestMatchers(HttpMethod.DELETE, "/api/**").hasRole("ADMIN");
authorize.requestMatchers(HttpMethod.GET, "/api/**").hasAnyRole("ADMIN", "USER");
authorize.requestMatchers(HttpMethod.PATCH, "/api/**").hasAnyRole("ADMIN", "USER");
authorize.anyRequest().authenticated();
}).httpBasic(Customizer.withDefaults());
http.exceptionHandling( exception -> exception
.authenticationEntryPoint(authenticationEntryPoint));
http.addFilterBefore(authenticationFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
The SecurityFilterChain is responsible for specifying how security should be applied to HTTP requests in a Spring application.The authorizeHttpRequests() method specifies authorization rules for HTTP requests based on URLs and HTTP methods.
authorize.requestMatchers(HttpMethod.POST, "/api/**").hasRole("ADMIN"): Specifies that only users with the "ADMIN" role are allowed to make POST requests to any URL that matches the /api/** pattern.
Similar rules are set for PUT, DELETE, GET, and PATCH requests. For PUT, DELETE, and PATCH methods, only "ADMIN" users are allowed. For GET requests, both "ADMIN" and "USER" roles are permitted, providing broader access.
authorize.anyRequest().authenticated(): This rule ensures that any request not matching the previous patterns must be authenticated, regardless of the user's role. It is a catch-all rule that secures all other endpoints.
Method-Level Security
@RestController
@RequestMapping("/api/")
public class AdminController {
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin")
public ResponseEntity<String> helloAdmin(){
return ResponseEntity.ok("Hello Admin");
}
@PreAuthorize("hasRole('USER')")
@GetMapping("/user")
public ResponseEntity<String> helloUser(){
return ResponseEntity.ok("Hello User");
}
}
Comments
Post a Comment
Leave Comment