Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 38

Method-Level Security with @PreAuthorize for Role-Based Endpoint Access

This lesson is built with resources from youtube.com, blog.tericcabrel.com and 1 more site.

Hello! Welcome back.

In the last lesson, we built a JwtAuthenticationFilter that successfully validates a user's JWT and establishes their identity within Spring Security's SecurityContext. We've solved the authentication problem: we know who the user is. Now, we'll tackle authorization: controlling what a user is allowed to do.

This lesson directly addresses the learning outcome: Secure endpoints based on user roles (e.g., USER, ADMIN) using method-level security with @PreAuthorize. We will create specific endpoints that are only accessible to users with an 'ADMIN' role, adding a critical layer of security to our application.

MERN-to-Spring Mapping: Authorization Middleware

In an Express.js application, you would typically implement role-based access control (RBAC) by chaining another middleware function after your JWT authentication middleware. This function would inspect the user object attached to the request (e.g., req.user.role) and either call next() or send a 403 Forbidden response.

// Express.js example
const isAdmin = (req, res, next) => {
  if (req.user && req.user.role === 'admin') {
    return next();
  }
  return res.status(403).send('Access Denied: Admins only');
};

app.get('/api/admin/dashboard', authenticateToken, isAdmin, (req, res) => {
  // ... admin logic
});

Spring Security provides a more declarative and powerful way to achieve the same result using method-level security annotations. Instead of manually writing if/else logic in a filter or middleware, we will annotate our methods directly to specify the required roles.


1. Updating the Data Model for Roles

First, our application needs to understand the concept of roles. We'll start by defining USER and ADMIN roles and associating them with our User entity.

Step 1: Create a Role Enum

An enum is the perfect way to represent a fixed set of roles. In your entities package, create a new Java enum called Role.java.

// src/main/java/com/example/blogplatform/entities/Role.java
package com.example.blogplatform.entities;

public enum Role {
    USER,
    ADMIN
}

Step 2: Add the Role to the User Entity

Now, let's add a role field to our User entity. The @Enumerated(EnumType.STRING) annotation tells JPA to store the role's name (e.g., "USER" or "ADMIN") as a string in the database, which is more readable than using its ordinal value (0 or 1).

Open User.java and add the following field and update the builder:

// src/main/java/com/example/blogplatform/entities/User.java

// ... imports
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "users") // Use a plural name for the table
public class User implements UserDetails {
    // ... existing fields (id, firstname, lastname, email, password)

    @Enumerated(EnumType.STRING)
    private Role role;

    // ... existing methods
}

Step 3: Connect Roles to Spring Security's Authorities

This is the most critical step. Spring Security doesn't work with our Role enum directly. It works with a concept called GrantedAuthority. We must override the getAuthorities() method in our User entity to tell Spring Security what authorities (in our case, roles) the user has.

Update the getAuthorities() method in User.java:

// src/main/java/com/example/blogplatform/entities/User.java

// ... imports
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import java.util.List;


// ... inside the User class
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    // Spring Security expects roles to be in the format 'ROLE_YOUR_ROLE'
    return List.of(new SimpleGrantedAuthority("ROLE_" + role.name()));
}

Why ROLE_? By convention, Spring Security's hasRole() expression automatically looks for authorities that start with the ROLE_ prefix. By adding it here, we make our lives easier when we write our security rules later.

Finally, update the AuthenticationService to assign the USER role to all new signups.

// In src/main/java/com/example/blogplatform/service/AuthenticationService.java

// ...
import com.example.blogplatform.entities.Role;

// ... inside the register method
var user = User.builder()
        .firstname(request.getFirstname())
        .lastname(request.getLastname())
        .email(request.getEmail())
        .password(passwordEncoder.encode(request.getPassword()))
        .role(Role.USER) // Set the default role
        .build();
// ...

2. Enabling Method-Level Security

To use annotations like @PreAuthorize, you must first enable this capability in the security configuration. Add the @EnableMethodSecurity annotation to your SecurityConfig class.

// In src/main/java/com/example/blogplatform/config/SecurityConfig.java

import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableMethodSecurity // Add this annotation
public class SecurityConfig {
    // ... rest of the class
}

This annotation tells Spring to scan for security annotations on your beans and wrap them with proxies to enforce the rules. We'll explore what "proxies" mean in the debugging section.


3. Securing an Endpoint with @PreAuthorize

Let's create an admin-only endpoint and protect it.

  1. Create a new controller called AdminController.java.
  2. Add a simple GET endpoint.
  3. Add the @PreAuthorize("hasRole('ADMIN')") annotation to the method.
// src/main/java/com/example/blogplatform/controller/AdminController.java
package com.example.blogplatform.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1/admin")
public class AdminController {

    @GetMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<String> sayHelloToAdmin() {
        return ResponseEntity.ok("Hello, Admin!");
    }
}

The string "hasRole('ADMIN')" is written in Spring Expression Language (SpEL). At runtime, Spring will evaluate this expression against the currently authenticated user's authorities. If the user has the ROLE_ADMIN authority, the method is executed. If not, an AccessDeniedException is thrown, which results in a 403 Forbidden response.


4. Runtime Observation and Debugging

Theory is one thing; seeing it live is another. Let's set up our test environment.

Step 1: Seed an Admin User on Startup

We need an admin user to test with. A great pattern for development is to use a CommandLineRunner to create necessary data when the application starts.

Create a new configuration class SeedDataConfig.java in your config package.

package com.example.blogplatform.config;

import com.example.blogplatform.entities.Role;
import com.example.blogplatform.entities.User;
import com.example.blogplatform.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
@RequiredArgsConstructor
@Slf4j
public class SeedDataConfig implements CommandLineRunner {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    @Override
    public void run(String... args) throws Exception {
        String adminEmail = "admin@example.com";
        Optional<User> existingAdmin = userRepository.findByEmail(adminEmail);

        if (existingAdmin.isEmpty()) {
            var adminUser = User.builder()
                    .firstname("Admin")
                    .lastname("User")
                    .email(adminEmail)
                    .password(passwordEncoder.encode("password"))
                    .role(Role.ADMIN)
                    .build();
            userRepository.save(adminUser);
            log.info("Created ADMIN user: {}", adminEmail);
        } else {
            log.info("ADMIN user already exists: {}", adminEmail);
        }
    }
}

Now, when you restart your application, an admin user will be created automatically if one doesn't already exist.

Step 2: Test the Authorization Flow

  1. Restart your application.
  2. Test as a Regular User (expect failure):
    • Register a new user via POST /api/auth/register.
    • Log in with that user's credentials via POST /api/auth/login to get an access token.
    • In Postman, make a GET request to http://localhost:8080/api/v1/admin with this user's Bearer Token.
    • Result: You will receive a 403 Forbidden status. The system authenticated you but determined you are not authorized.
  3. Test as an Admin User (expect success):
    • Log in as the admin user (admin@example.com, password) via POST /api/auth/login to get an admin access token.
    • Make a GET request to http://localhost:8080/api/v1/admin with the admin's Bearer Token.
    • Result: You will receive a 200 OK with the message "Hello, Admin!".

Step 3: Debugging the Internals (AOP Proxies)

Your preference for debugging is the best way to understand how @PreAuthorize works. It's not magic; it's Aspect-Oriented Programming (AOP).

When you added @EnableMethodSecurity, you told Spring to create a proxy around your AdminController. This proxy is an object that wraps your controller and intercepts calls to its methods.

Proxy Design Pattern Illustration
This diagram shows the Proxy pattern. Your client code (the DispatcherServlet) calls the Proxy, not the real Target (your controller). The Proxy checks the @PreAuthorize annotation before deciding whether to call the real method on the Target.

Let's see the more detailed flow:

Spring Method-Level Security Flow with @PreAuthorize and @PostAuthorize
This diagram shows the internal mechanics. When your controller method is called, the `AuthorizationManagerBeforeMethodInterceptor` (the AOP proxy) intercepts it. It evaluates the SpEL expression (`hasRole('ADMIN')`) against the `Authentication` object from the `SecurityContextHolder`. If it passes, the method proceeds. If not, it throws an `AccessDeniedException`.

Your Debugging Task:

  1. Set a breakpoint inside your JwtAuthenticationFilter where the SecurityContextHolder is populated.
  2. Run the application in Debug mode and make a request with the admin token.
  3. Inspect the authToken object. Expand userDetails -> authorities. You will see a SimpleGrantedAuthority with role set to ROLE_ADMIN. This is the data the proxy will check against.
  4. Spring's AOP magic is deep, so you can't easily step into the proxy check itself, but by observing the Authentication object, you can confirm that the necessary data is present for the check to succeed.

5. Architectural Best Practice: Secure the Service Layer

Right now, we've secured the web layer (the controller). But what if another part of your application calls the business logic directly, bypassing the controller?

  • Another service in a microservices architecture.
  • A scheduled task running with @Scheduled.
  • A future developer reusing your service in a new controller without realizing it needs security.

This is why a production-grade application applies defense-in-depth. The security rule should live with the business logic it protects.

Let's refactor to secure the service layer.

  1. Create an AdminService:

    // src/main/java/com/example/blogplatform/service/AdminService.java
    package com.example.blogplatform.service;
    
    import org.springframework.security.access.prepost.PreAuthorize;
    import org.springframework.stereotype.Service;
    
    @Service
    public class AdminService {
    
        @PreAuthorize("hasRole('ADMIN')")
        public String getAdminMessage() {
            // This is the business logic we want to protect
            return "Hello, Admin!";
        }
    }
    
  2. Update the AdminController to call the service:

    // src/main/java/com/example/blogplatform/controller/AdminController.java
    
    // ... imports
    import com.example.blogplatform.service.AdminService;
    import lombok.RequiredArgsConstructor;
    
    @RestController
    @RequestMapping("/api/v1/admin")
    @RequiredArgsConstructor // Use constructor injection
    public class AdminController {
    
        private final AdminService adminService;
    
        @GetMapping
        // We can remove @PreAuthorize from here now
        public ResponseEntity<String> sayHelloToAdmin() {
            return ResponseEntity.ok(adminService.getAdminMessage());
        }
    }
    

Now, the security rule is attached to the getAdminMessage() method itself. No matter how it's called—via a controller, another service, or a batch job—the authorization check will always be performed. This is a much more robust design.

You can learn more about this approach from the following reading.

Understanding @PreAuthorize in Spring Security Architecture

This article, 'Understanding @PreAuthorize in Spring Security Architecture', provides an excellent, concise explanation of why securing the service layer is a critical best practice.

Please read sections 5 ('Why controller-only security is dangerous') and the final 'Architect takeaway'. Focus on the reasoning behind defense-in-depth and why the service layer is considered the 'real security boundary'.


Conclusion

Congratulations! You have successfully implemented role-based authorization. You can now create endpoints and service methods that are restricted to specific user roles, a cornerstone of any secure, multi-user application.

Key Takeaways:

  • Roles & Authorities: We represent roles in our domain (Role enum) and expose them to Spring Security as GrantedAuthority objects via the getAuthorities() method.
  • Method Security: The @EnableMethodSecurity annotation activates method-level security checks.
  • @PreAuthorize: This powerful annotation uses Spring Expression Language (SpEL) like hasRole('ADMIN') to declare authorization rules directly on methods.
  • Defense-in-Depth: For robust, enterprise-grade security, authorization rules should be placed on the service layer, not just the controller layer, to protect the business logic itself.

Preview of the Next Lesson:

Currently, we are passing our JWTs in the Authorization header, which is standard for many APIs. However, for web browser clients, there's a more secure way to handle tokens that helps mitigate Cross-Site Scripting (XSS) attacks. In the next lesson, we will deliver tokens to the client via secure, HTTP-only cookies.