Baeldung

Java, Spring and Web Development tutorials

 

Authorize Request for Certain URL and HTTP Method in Spring Security
2025-06-07 10:31 UTC by Oscar Ramadhan

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.

As always, the source code for this article is available over on GitHub.

The post Authorize Request for Certain URL and HTTP Method in Spring Security first appeared on Baeldung.
 

Content mobilized by FeedBlitz RSS Services, the premium FeedBurner alternative.