eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

Course – LSS – NPI (cat=Spring Security)
announcement - icon

If you're working on a Spring Security (and especially an OAuth) implementation, definitely have a look at the Learn Spring Security course:

>> LEARN SPRING SECURITY

1. Overview

Securing resources based on user roles and HTTP methods in web application development is essential to prevent unauthorized access and manipulation. Spring Security provides a flexible and powerful mechanism to restrict or allow access to certain endpoints based on user roles and HTTP request types. Authorization in Spring Security restricts access to certain parts of the application based on the current user’s roles or authorities.

In this tutorial, we’ll explore how to authorize requests for specific URLs and HTTP methods using Spring Security. We’ll go through the configuration, learn how it works behind the scenes, and demonstrate its implementation in a simple blogging platform.

2. Set up Project

Before implementing the features, we must set up our project with the necessary dependencies and configurations. Our sample blogging platform needs to:

  • Allow public registration (/users/register) without authentication
  • Allow authenticated users (with the USER role) to create, view, update, and delete their posts
  • Allow administrators (with the ADMIN role) to delete any post
  • Provide open access to the H2 database console (/h2-console) for development and testing purposes

2.1. Maven Dependency

Let’s start by ensuring spring-boot-starter-security, spring-boot-starter-data-jpa, spring-boot-starter-web, and h2-database are added to the project in our pom.xml file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <version>3.4.4</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
    <version>3.4.4</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
    <version>3.4.4</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>3.4.4</version>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>2.3.232</version>
</dependency>

2.2. Application Properties

Now, let’s set our application.properties file for H2 database needs:

spring.application.name=spring-security

spring.datasource.url=jdbc:h2:file:C:/your_folder_here/test;DB_CLOSE_DELAY=-1;IFEXISTS=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=qwerty

spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

3. Configuration

Let’s define a SecurityConfig class to control access to specific URLs and HTTP methods:

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
          .csrf(csrf -> csrf.disable())
          .headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable))
          .authorizeHttpRequests(auth -> auth
            .requestMatchers(new AntPathRequestMatcher("/users/register")).permitAll()
            .requestMatchers(new AntPathRequestMatcher("/h2-console/**")).permitAll()
            .requestMatchers(HttpMethod.GET, "/users/profile").hasAnyRole("USER", "ADMIN")
            .requestMatchers(HttpMethod.GET, "/posts/mine").hasRole("USER")
            .requestMatchers(HttpMethod.POST, "/posts/create").hasRole("USER")
            .requestMatchers(HttpMethod.PUT, "/posts/**").hasRole("USER")
            .requestMatchers(HttpMethod.DELETE, "/posts/**").hasAnyRole("USER", "ADMIN")
            .anyRequest().authenticated()
          )
        .httpBasic(Customizer.withDefaults());

        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

This SecurityConfig class configures the security settings for a Spring-based web application using Spring Security. Let’s walk through what this configuration does:

  • @Configuration indicates that this class provides Spring configuration
  • @EnableWebSecurity enables Spring Security’s web security support
  • @EnableMethodSecurity allows method-level security using annotations like @PreAuthorize
  • SecurityFilterChain bean customizes HTTP security settings in the HttpSecurity object
  • Disable CSRF protection, which is typically done for stateless APIs or during development
  • Disables frame options headers to allow access to the H2 console, which uses iframes
  • Allows unauthenticated access to /users/** endpoints (e.g., registration) and the /h2-console/** endpoint for the embedded H2 database console
  • Restricts access to user-specific post operations (GET, POST, PUT) to users with the USER role
  • Allows users with either the USER or ADMIN role to delete posts
  • Requires authentication for any other requests not explicitly mentioned
  • Enables basic HTTP authentication with default settings
  • Declares a PasswordEncoder bean using BCrypt, which is a secure algorithm for hashing passwords

This configuration ensures that the application has proper access control on endpoints, especially distinguishing between public and protected routes, and enforces role-based access for post-related actions.

4. Implementation

Now that we’ve finished the data model and security configuration, it’s time to implement the core application logic.

In this section, we’ll walk through how our app handles user registration, authentication, and post management, while enforcing method-level security based on user roles.

4.1. Register and Get Profile

We now implement a UserController to handle auth-related operations. The endpoints include:

  • Registering a new user (POST /users/register)
  • Retrieving the profile of the authenticated user (GET /users/profile)

The registration endpoint is publicly accessible, while the profile endpoint requires authentication:

@RestController
@RequestMapping("users")
public class UserController {
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("register")
    public ResponseEntity<String> register(@RequestBody RegisterRequestDto request) {
        String result = userService.register(request);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @GetMapping("profile")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
    public ResponseEntity<UserProfileDto> profile(Authentication authentication) {
        UserProfileDto userProfileDto = userService.profile(authentication.getName());
        return new ResponseEntity<>(userProfileDto, HttpStatus.OK);
    }
}

Now let’s create our DTOs:

public class RegisterRequestDto {
    private String username;
    private String email;
    private String password;
    private Role role;

    // constructor here
    // setter and getter here
}
public class UserProfileDto {
    private String username;
    private String email;
    private Role role;

    // constructor here
    // setter and getter here
}

4.2. Creating a Post

Let’s create a POST /posts/create endpoint to create a new post. Only users with the USER role are allowed to create posts:

@RestController
@RequestMapping("posts")
public class PostController {
    private final PostService postService;

    public PostController(PostService postService) {
        this.postService = postService;
    }

    @PostMapping("create")
    @PreAuthorize("hasRole('USER')")
    public ResponseEntity<PostResponseDto> create(@RequestBody PostRequestDto dto, Authentication auth) {
        PostResponseDto result = postService.create(dto, auth.getName());
        return new ResponseEntity<>(result, HttpStatus.CREATED);
    }
}

This method delegates post creation to the service layer. It also uses the Spring Authentication object to identify the currently logged-in user.

The @PreAuthorize annotation in Spring Security controls access before a method is executed. It checks whether the currently authenticated user has the required role or permission to access the method.

4.3. Listing Users’ Posts

Now, let’s create a GET /posts/mine endpoint to allow users to view only their posts:

@GetMapping("mine")
@PreAuthorize("hasRole('USER')")
public ResponseEntity<List<PostResponseDto>> myPosts(Authentication auth) {
    List<PostResponseDto> result = postService.myPosts(auth.getName());
    return new ResponseEntity<>(result, HttpStatus.OK);
}

4.4. Updating a Post

Let’s create a PUT /posts/{id} endpoint so users can update their posts:

@PutMapping("{id}")
@PreAuthorize("hasRole('USER')")
public ResponseEntity<String> update(@PathVariable Long id, @RequestBody PostRequestDto req, Authentication auth) {
    try {
        postService.update(id, req, auth.getName());
        return new ResponseEntity<>("updated", HttpStatus.OK);
    } catch (AccessDeniedException ade) {
        return new ResponseEntity<>(ade.getMessage(), HttpStatus.FORBIDDEN);
    }
}

4.5. Deleting a Post

Next, let’s create a DELETE /posts/{id} endpoint so users can delete their posts, and admins can delete any post:

@DeleteMapping("{id}")
@PreAuthorize("hasAnyRole('USER', 'ADMIN')")
public ResponseEntity<?> delete(@PathVariable Long id, Authentication auth) {
    try {
        boolean isAdmin = auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"));
        postService.delete(id, isAdmin, auth.getName());
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    } catch (AccessDeniedException ade) {
        return new ResponseEntity<>(ade.getMessage(), HttpStatus.FORBIDDEN);
    } catch (NoSuchElementException nse) {
        return new ResponseEntity<>(nse.getMessage(), HttpStatus.NOT_FOUND);
    }
}

We use @PreAuthorize to check roles on method-level, so only the USER role can get, update, or delete their posts unless they’re an admin. In this sample, the USER and the ADMIN roles can access the delete endpoint, but the code ensures that regular users can only delete their posts. Only ADMINs are allowed to delete posts created by other users.

Now, let’s create our DTOs for this controller:

public class PostRequestDto {
    private String title;
    private String content;

    // constructor here
    // setter and getter here
}

4.6. Creating a UserService

We create a service class that implements our authentication logic to handle user-related operations such as registration and profile retrieval. Below is the implementation of the UserService class, which provides methods to register new users and fetch user details based on authentication:

@Service
public class UserService {
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }

    public String register(RegisterRequestDto request) {
        if (userRepository.findByUsername(request.getUsername()).isPresent()) {
            return "Username already exists";
        }

        User user = new User();
        user.setUsername(request.getUsername());
        user.setEmail(request.getEmail());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setRole(request.getRole());

        userRepository.save(user);
        return "User registered successfully";
    }

    public UserProfileDto profile(String username) {
        Optional<User> user = userRepository.findByUsername(username);
        return user.map(value -> new UserProfileDto(value.getUsername(), value.getEmail(), value.getRole())).orElseThrow();
    }

    public User getUser(String username) {
        Optional<User> user = userRepository.findByUsername(username);
        return user.orElse(null);
    }
}

This service performs three key functions:

  • register() checks whether the username is already taken, hashes the password using BCrypt, and saves the new user to the database
  • profile() extracts the current user’s identity from the Authentication object and maps it to a UserProfileDto
  • getUser() provides direct access to the User entity, which can be useful in other parts of the application where the full User object is needed

With this service in place, we can integrate user registration and profile functionality into our controllers and ensure secure handling of sensitive data like passwords.

4.7. Creating a UserDetailService

To enable Spring Security to authenticate users based on the data in our database, we need to implement a custom UserDetailsService. This service is responsible for loading user-specific data during the authentication process. Here’s how we can achieve that using the CustomUserDetailService class:

@Service
public class CustomUserDetailService implements UserDetailsService {
    private final UserRepository userRepository;

    public CustomUserDetailService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username)
          .orElseThrow(() -> new UsernameNotFoundException("User not found"));

        return org.springframework.security.core.userdetails.User
          .withUsername(user.getUsername())
          .password(user.getPassword())
          .roles(user.getRole().name())
          .build();
    }
}

This CustomUserDetailService class does the following:

  • Implements UserDetailsService, a core interface in Spring Security used to retrieve user information.
  • Inside loadUserByUsername(), it fetches the user by username from the database. If the user doesn’t exist, it throws a UsernameNotFoundException.
  • Builds and returns a Spring Security UserDetails object using the username, password, and role from our User entity.

By providing this custom implementation, Spring Security can integrate seamlessly with our application’s user data, enabling secure and role-based access control throughout the system.

4.8. Creating a PostService

The PostService class handles all the business logic related to post management in the application. It interacts with the PostRepository for data persistence and with the UserService to retrieve authenticated user information. Let’s break down its implementation:

@Service
public class PostService {
    private final PostRepository postRepository;
    private final UserService userService;

    public PostService(PostRepository postRepository, UserService userService) {
        this.postRepository = postRepository;
        this.userService = userService;
    }

    public PostResponseDto create(PostRequestDto req, String username) {
        User user = userService.getUser(username);
        Post post = new Post();
        post.setTitle(req.getTitle());
        post.setContent(req.getContent());
        post.setUser(user);
        return toDto(postRepository.save(post));
    }

    public void update(Long id, PostRequestDto dto, String username) {
        Post post = postRepository.findById(id).orElseThrow();
        if (!post.getUser().getUsername().equals(username)) {
            throw new AccessDeniedException("You can only edit your own posts");
        }
        post.setTitle(dto.getTitle());
        post.setContent(dto.getContent());
        postRepository.save(post);
    }

    public void delete(Long id, boolean isAdmin, String username) {
        Post post = postRepository.findById(id).orElseThrow();
        if (!isAdmin && !post.getUser().getUsername().equals(username)) {
            throw new AccessDeniedException("You can only delete your own posts");
        }
        postRepository.delete(post);
    }

    public List<PostResponseDto> myPosts(String username) {
        User user = userService.getUser(username);
        return postRepository.findByUser(user).stream().map(this::toDto).toList();
    }

    private PostResponseDto toDto(Post post) {
        return new PostResponseDto(post.getId(), post.getTitle(), post.getContent(), post.getUser().getUsername());
    }
}

This PostService class handles:

  • Creating posts to allow authenticated users to create a new post
  • Updating posts to allow authenticated users to update their posts, attempting to update others’ posts results in an access denial
  • Deleting posts allows users to delete their posts, while admins have the privilege to delete any post
  • Viewing personal posts allows users to retrieve a list of their posts

The use of Authentication ensures that every operation respects user identity and role-based access control. This service layer separates business logic from controller logic, keeping the architecture clean and maintainable.

5. Conclusion

In this article, we learned how to secure HTTP requests in a Spring Boot application by configuring Spring Security to:

  • Grant or restrict access to specific endpoints based on roles
  • Control access based on HTTP methods
  • Apply method-level authorization using @PreAuthorize

This structure not only keeps the application secure but also ensures proper role-based data ownership and access control, which is crucial in any multi-user system.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LSS – NPI (cat=Security/Spring Security)
announcement - icon

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments