How Can Spring Security Use @PreAuthorize on Controller Methods?

Question

How can Spring Security use @PreAuthorize on controller methods?

@RestController
public class MyController {

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/admin")
    public ResponseEntity<String> getAdminData() {
        return ResponseEntity.ok("Admin data");
    }
}

Answer

In Spring Security, the @PreAuthorize annotation allows you to specify authorization constraints on your controller methods. By applying this annotation, you can ensure that only users with the designated roles or permissions can access specific endpoints in your application.

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/admin").hasRole("ADMIN")
            .anyRequest().authenticated();
    }
}

Causes

  • User does not have the required role or permission.
  • Security configuration is not properly set up to recognize @PreAuthorize.
  • Missing dependency for Aspect-Oriented Programming (AOP) support.

Solutions

  • Ensure the correct role or permission is granted to the user trying to access the resource.
  • Verify that your Spring Security configuration includes method security enabled with @EnableGlobalMethodSecurity(prePostEnabled = true).
  • Add 'spring-boot-starter-aop' dependency if not already included in your project.

Common Mistakes

Mistake: Not enabling method security in the configuration.

Solution: Make sure to add @EnableGlobalMethodSecurity(prePostEnabled = true) in your configuration.

Mistake: Incorrect SpEL expressions in @PreAuthorize annotations.

Solution: Double-check your SpEL expressions and user roles.

Helpers

  • Spring Security
  • @PreAuthorize
  • Spring controllers
  • method security
  • authorization in Spring

Related Questions

⦿What is the Scala Equivalent of `java.util.ArrayList`?

Discover the Scala equivalent of Javas ArrayList and understand key differences between the two collections.

⦿Why Are Java 8 Lambdas Invoked with invokedynamic?

Discover why Java 8 uses invokedynamic for lambda expressions despite having static methods and understand its performance implications.

⦿Understanding the Purpose of Guava's checkNotNull Method

Learn why Guavas checkNotNull method is important for null checks in Java including its benefits and usage with code examples.

⦿How to Resolve the 'Cannot Find Symbol' Error When Using Kotlin Class in Java with Maven?

Learn how to fix the Cannot find symbol error when referencing a Kotlin class in Java using Maven. Follow our expert guide for troubleshooting.

⦿Understanding the Differences Between getLocationOnScreen() and getLocationInWindow() Methods in Android

Explore the distinctions between getLocationOnScreen and getLocationInWindow methods in Android along with practical examples and best practices.

⦿How to Cache Maven Dependencies in a Docker Image for Faster Builds?

Learn how to create a Docker image that caches Maven dependencies reducing build time and improving efficiency. Stepbystep guide included.

⦿Understanding the Output of the Java equals Method in a Custom Class

Learn why the equals method in Java returns specific outputs with detailed code breakdown and common mistakes.

⦿How to Rename a Class and Its Corresponding File in Eclipse?

Learn how to efficiently rename a Java class and its file in Eclipse IDE ensuring proper updates to all references.

⦿Understanding NoSuchBeanDefinitionException in Spring Framework and How to Resolve It

Learn about NoSuchBeanDefinitionException in Spring Framework what it means its causes and how to fix it effectively.

⦿Is It Possible to Overload the Main Method in Java?

Discover how to overload the main method in Java and explore usage examples common mistakes and debugging tips.

© Copyright 2025 - CodingTechRoom.com