Spring Boot Method-Level Security

Welcome, in this tutorial, we will see how to implement method-level security in a spring boot application. We will use the @PreAuthorize annotation to handle the method-level security and will also understand the difference between @Secured and @PreAuthorize annotations.

1. Introduction

Before going further in this tutorial, we will look at the common terminology such as introduction to Spring Boot and Lombok.

1.1 Spring Boot

  • Spring boot is a module that provides rapid application development feature to the spring framework including auto-configuration, standalone-code, and production-ready code
  • It creates applications that are packaged as jar and are directly started using embedded servlet container (such as Tomcat, Jetty or, Undertow). Thus, no need to deploy the war files
  • It simplifies the maven configuration by providing the starter template and helps to resolve the dependency conflicts. It automatically identifies the required dependencies and imports them into the application
  • It helps in removing the boilerplate code, extra annotations, and XML configurations
  • It provides powerful batch processing and manages the rest endpoints
  • It provides an efficient JPA-starter library to effectively connect the application with the relational databases
  • It offers a Microservice architecture and cloud configuration that manages all the application related configuration properties in a centralized manner

1.2 Lombok

  • Lombok is nothing but a small library that reduces the amount of boilerplate Java code from the project
  • Automatically generates the getters and setters for the object by using the Lombok annotations
  • Hooks in via the Annotation processor API
  • Raw source code is passed to Lombok for code generation before the Java Compiler continues. Thus, produces properly compiled Java code in conjunction with the Java Compiler
  • Under the target/classes folder you can view the compiled class files
  • Can be used with Maven, Gradle IDE, etc.

1.2.1 Lombok features

valLocal variables are declared as final
varMutable local variables
@Slf4JCreates an SLF4J logger
@CleanupWill call close() on the resource in the finally block
@GetterCreates getter methods for all properties
@SetterCreates setter for all non-final properties
  • Generates implementations of equals(Object other) and hashCode()
  • By default will use all non-static, non-transient properties
  • Can optionally exclude specific properties
  • Generates String of class name, and each field separated by commas
  • Optional parameter to include field names
  • Optional parameter to include a call to the super toString method
  • Generates no-args constructor
  • Will cause compiler error if there are final fields
  • Can optionally force, which will initialize final fields with 0/false/null var – mutable local variables
  • Generates a constructor for all fields that are final or marked @NonNull
  • The constructor will throw a NullPointerException if any @NonNull fields are null val – local variables are declared final
  • Generates a constructor for all properties of the class
  • Any @NotNull properties will have null checks
  • Generates typical boilerplate code for POJOs
  • Combines – @Getter, @Setter, @ToString, @EqualsAndHashCode, @RequiredArgsConstructor
  • No constructor is generated if constructors have been explicitly declared
  • Implements the Builder pattern for object creation
  • The immutable variant of @Data
  • All fields are made private and final by default

Let us go ahead with the tutorial implementation but before going any further I’m assuming that you’re aware of the Spring boot basics.

2. Spring Boot Method-Level Security

2.1 Tools Used for Spring boot application and Project Structure

We are using Eclipse Kepler SR2, JDK 8, and Maven. In case you’re confused about where you should create the corresponding files or folder, let us review the project structure of the spring boot application.

spring boot method security -project structure
Fig. 1: Project structure

Let us start building the application!

3. Creating a Spring Boot application

Below are the steps involved in developing the application.

3.1 Maven Dependency

Here, we specify the dependency for the Spring boot (Web, JPA, and Security), H2 database, and Lombok. The updated file will have the following code.


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="" xmlns=""
        <relativePath/> <!-- lookup parent from repository -->
    <description>Method level security in springboot application</description>






3.2 Application properties file

Create a new properties file at the location: SpringbootMethodlevelsecurity/src/main/resources/ and add the following code to it. Here we will define the H2 database connection, database creation, and h2 console details. You’re free to change the application or the database details as per your wish.

# h2 database settings
# db-creation settings
## browser url for h2 console - http://localhost:9800/h2-console

3.3 Java Classes

Let us write the important java class(es) involved in this application. For brevity, we will skip the following classes –

  • – Entity class to persist the data in the database
  • – Enum class that contains the role constants for the users
  • – Repository interface that extends the JpaRepository interface to perform the SQL operations. The interface provides an explicit implementation to the findByUsername method and returns an optional
  • – Service class that interact with the DAO layer methods
  • – Bootstrap class to populate dummy data to the h2 database once the application is started successfully
  • – Response DTO to be used by the service layer method for sending out the get all users response. It is basically acting as a mapper to the class

3.3.1 Implementation/Main class

Add the following code to the main class to bootstrap the application from the main method. Always remember, the entry point of the spring boot application is the class containing @SpringBootApplication annotation and the static main method.


import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

//lombok annotation
//spring annotation
public class SpringbootMethodlevelsecurityApplication {

    public static void main(String[] args) {, args);"Spring boot and method-level security application started successfully");

3.3.2 Model class

Add the following code to the model class that will be used to map the User object during the find user by username operation. The class will implement the UserDetails interface provided by the spring security. The implementation of this class can be seen in the class.


import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class CustomUserDetails implements UserDetails {

    private static final long serialVersionUID = 1L;

    private final String username;
    private final String password;
    private final boolean isActive;
    private final List<GrantedAuthority> authorities;

    public CustomUserDetails(final User user) {
        this.username = user.getUsername();
        this.password = user.getPassword();
        this.isActive = user.isActive();
        this.authorities = getAuthorities(user.getRoles());

    private List<GrantedAuthority> getAuthorities(final List<Role> roles) {
        //checking the null and empty check
        if (CollectionUtils.isEmpty(roles)) {
            return Collections.emptyList();
        return -> new SimpleGrantedAuthority(role.toString())).collect(Collectors.toList());

    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;

    public String getPassword() {
        return password;

    public String getUsername() {
        return username;

    public boolean isAccountNonExpired() {
        return true;

    public boolean isAccountNonLocked() {
        return true;

    public boolean isCredentialsNonExpired() {
        return true;

    public boolean isEnabled() {
        return isActive;

3.3.3 User details service class

Add the following code to the custom user details service class that implements the UserDetailsService interface to provide an implementation to the loadUserByUsername method. The overridden method will interact with the DAO layer method to get the user.


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

//lombok annotation
//spring annotation
public class CustomUserDetailsService implements UserDetailsService {

    UserRepository repository;

    //find user by username from the db
    public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {"Fetching user = {}", username);
        final Optional<User> optionalUser = repository.findByUsername(username);
                () -> new UsernameNotFoundException(String.format("User = %s does not exists", username)));

3.3.4 Security config class

The security config is an important class that helps to enable fine-grained control over the authentication and authorization process. In this –

  • We will extend the WebSecurityConfigurerAdapter class
  • Override the configure(..) method to provide implementation to the AuthenticationManagerBuilder class. In this tutorial, we will use the UserDetailsService
  • Override another variation of configure(..) method to define the security mechanism for our application and define the protected and non-protected endpoints of the application
  • Annotate the class with the @EnableGlobalMethodSecurity annotation to enable the method-level security
  • A password encoder for encoding purposes as spring security expects an encoder to the present. If you don’t want this simply remove this method and add the {noop} parameter before the password. The {noop} parameter prevent an error related to PasswordEncode not present


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

//spring annotation
//spring security annotations
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String[] WHITELIST_PATTERNS = {"/api/anonymous", "/h2-console/**"};

    UserDetailsService detailsService;

    protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
        //using the user details service to authenticate the user from the db

    protected void configure(final HttpSecurity http) throws Exception {
        http.httpBasic()    // using the basic authentication
                .and().authorizeRequests().antMatchers(WHITELIST_PATTERNS).permitAll()      //public endpoints
                .and().authorizeRequests().anyRequest().authenticated()     // all other application endpoints are protected
        //do not create a session
        //effective for rest api's

    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();

3.3.5 Controller class

Add the following code to the controller class. The controller class contains methods that are annotated with the @PreAuthorize annotation that will check for authorization before the method execution. We could also use the @Secured annotation to handle the method-level security in spring but it has certain drawbacks i.e.

  • With @Secured annotation we cannot have multiple conditions i.e. the roles cannot be combined with an AND/OR condition
  • @Secured annotation does not support spring expression language


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

//lombok annotation
//spring annotations
public class SecurityController {

    UserService service;

    //note - @PreAuthorize checks for authorization before method execution

    //will be publicly accessible
    //URL - http://localhost:9800/api/anonymous
    public String getAnonymousResponse() {"Returning anonymous response");
        return "Hello anonymous";

    //will only be accessible by the user who has ROLE_USER assigned
    //URL - http://localhost:9800/api/protected/user
    public String getUserResponse() {"Returning user response");
        return "Hello user";

    //will be accessible by the users who has ROLE_MODERATOR assigned
    //URL - http://localhost:9800/api/protected/moderator
    public String getModeratorResponse() {"Returning moderator response");
        return "Hello moderator";

    //will be accessible by the users who has ROLE_ADMIN assigned
    //URL - http://localhost:9800/api/protected/admin
    public String getAdminResponse() {"Returning administrator response");
        return "Hello administrator";

    //will only be accessible by the user who has both ROLE_MODERATOR and ROLE_ADMIN assigned
    //URL - http://localhost:9800/api/protected/owner
    @PreAuthorize("hasRole('MODERATOR') AND hasRole('ADMIN')")
    public String getAppOwnerResponse() {"Returning application owner response response");
        return "Hello application owner";

    //will only be accessible by the user who has both ROLE_MODERATOR and ROLE_ADMIN assigned
    //URL - http://localhost:9800/api/protected/get-all-users
    @PreAuthorize("hasRole('MODERATOR') AND hasRole('ADMIN')")
    public List<UserDto> getUsers() {"Returning all users");
        return service.getUsers();

4. Run the Application

To execute the application, right-click on the class, Run As -> Java Application.

spring boot method security - run the application
Fig. 2: Run the Application

5. Project Demo

When the application is started, open the Postman tool to hit the application endpoints. Remember to specify the authorization details in each request. You can do so through the Authorization tab dropdown to select an auth type for every request. For this tutorial, we will select the auth type as Basic Auth where you will specify the username and password (refer to class to get the users and their associated roles information).

Application endpoints

-- HTTP GET endpoints –
-- Remember to include the authorization header containing the valid basic auth in each request –

//will be publicly accessible

//will only be accessible by the user who has ROLE_USER assigned

//will be accessible by the users who have ROLE_MODERATOR assigned

//will be accessible by the users who have ROLE_ADMIN assigned

//will only be accessible by the user who has both ROLE_MODERATOR and ROLE_ADMIN assigned

//will only be accessible by the user who has both ROLE_MODERATOR and ROLE_ADMIN assigned

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Summary

In this section, you learned:

  • Spring boot and Lombok introduction
  • Steps to implement method-level security in a spring boot application

You can download the sample application as an Eclipse project in the Downloads section.

7. Download the Project

This was an example of implementing method-level security in a spring boot application.

You can download the full source code of this example here: Spring Boot Method-Level Security

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions



An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button