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 – Diagrid – NPI EA (cat= Testing)
announcement - icon

In distributed systems, managing multi-step processes (e.g., validating a driver, calculating fares, notifying users) can be difficult. We need to manage state, scattered retry logic, and maintain context when services fail.

Dapr Workflows solves this via Durable Execution which includes automatic state persistence, replaying workflows after failures and built-in resilience through retries, timeouts and error handling.

In this tutorial, we'll see how to orchestrate a multi-step flow for a ride-hailing application by integrating Dapr Workflows and Spring Boot:

>> Dapr Workflows With PubSub

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

We may wish to apply multiple security filters within the different paths of our Spring Boot applications.

In this tutorial, we’ll take a look at two approaches to customizing our security – via the use of @EnableWebSecurity and @EnableGlobalMethodSecurity.

To illustrate the differences, we’ll use a simple application that has some admin resources, authenticated user resources. We’ll also give it a section with public resources that we are happy for anyone to download.

2. Spring Boot Security

2.1. Maven Dependencies

Whichever approach we take, we first need to add the spring boot starter for security:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2.2. Spring Boot Auto-Configuration

With Spring Security on the classpath, Spring Boot Security Auto-Configuration‘s WebSecurityEnablerConfiguration activates @EnableWebSecurity for us.

This applies Spring’s default security configuration to our application.

Default security activates both HTTP security filters and the security filter chain and applies basic authentication to our endpoints.

3. Protecting Our Endpoints

For our first approach, let’s start by creating a MySecurityConfigurer class, making sure that we annotate it with @EnableWebSecurity.

@EnableWebSecurity
public class MySecurityConfigurer {
}

3.1. A Quick Look at SecurityFilterChain Bean

First, let’s take a look at  how to register a SecurityFilterChain bean:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.authorizeRequests((requests) -> requests.anyRequest().authenticated());
    http.formLogin(Customizer.withDefaults());
    http.httpBasic(Customizer.withDefaults());
    return http.build();
}

Here we see that any request we receive is authenticated, and we have a basic form login to prompt for credentials.

When we want to use the HttpSecurity DSL, we write this as:

http.authorizeRequests(request -> request.anyRequest().authenticated())
  .formLogin(Customizer.withDefaults())
  .httpBasic(Customizer.withDefaults())

3.2. Require Users to Have an Appropriate Role

Now let’s configure our security to allow only users with an ADMIN role to access our /admin endpoint. We’ll also allow only users with a USER role to access our /protected endpoint.

We achieve this by creating a SecurityFilterChain bean:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    return http.authorizeHttpRequests(request -> request.requestMatchers(new AntPathRequestMatcher("/admin/**"))
            .hasRole("ADMIN"))
        .authorizeHttpRequests(request -> request.requestMatchers(new AntPathRequestMatcher("/protected/**"))
            .hasRole("USER"))
        .build();
}

3.3. Relax Security for Public Resources

We don’t need authentication for our public /hello resources, so we’ll configure WebSecurity to do nothing for them.

Just like before, let’s  register a WebSecurityCustomizer bean:

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
    return (web) -> web.ignoring()
        .requestMatchers(new AntPathRequestMatcher("/public/*"));
}

4. Protect Our Endpoints Using Annotations

To apply security using an annotation-driven approach, we can use @EnableGlobalMethodSecurity.

4.1. Require Users to Have an Appropriate Role Using Security Annotations

Now let’s use method annotations to configure our security to allow only ADMIN users to access our /admin endpoint and our USER users to access our /protected endpoint.

Let’s enable JSR-250 annotations by setting jsr250Enabled=true in our EnableGlobalMethodSecurity annotation:

@EnableGlobalMethodSecurity(jsr250Enabled = true)
@Controller
public class AnnotationSecuredController {
    @RolesAllowed("ADMIN")
    @RequestMapping("/admin")
    public String adminHello() {
        return "Hello Admin";
    }

    @RolesAllowed("USER")
    @RequestMapping("/protected")
    public String jsr250Hello() {
        return "Hello Jsr250";
    }
}

4.2. Enforce All Public Methods Have Security

When we use annotations as our way of implementing security, we may forget to annotate a method. This would inadvertently create a security hole.

To safeguard against this, we should deny access to all methods that don’t have authorization annotations.

4.3. Allow Access to Public Resources

Spring’s default security enforces authentication to all our endpoints, whether we add role-based security or not.

Although our previous example applies security to our /admin and /protected endpoints, we still want to allow access to file-based resources in /hello.

Whilst we could extend WebSecurityAdapter again, Spring provides us a simpler alternative.

Having protected our methods with annotations, we can now add the WebSecurityCustomizer to open the /hello/* resources:

public class MyPublicPermitter implements WebSecurityCustomizer {
    public void customize(WebSecurity webSecurity) {
        webSecurity.ignoring()
          .antMatchers("/hello/*");
    }
}

Alternatively, we can simply create a bean that implements it inside our configuration class:

@Configuration
public class MyWebConfig {
    @Bean
    public WebSecurityCustomizer ignoreResources() {
        return (webSecurity) -> webSecurity
          .ignoring()
          .antMatchers("/hello/*");
    }
}

When Spring Security initializes, it invokes any WebSecurityCustomizers it finds, including ours.

5. Testing Our Security

Now that we have configured our security, we should check that it behaves as we intended.

Depending on the approach we chose for our security, we have one or two options for our automated tests. We can either send web requests to our application or invoke our controller methods directly.

5.1. Testing via Web Requests

For the first option, we’ll create a @SpringBootTest test class with a @TestRestTemplate:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT)
public class WebSecuritySpringBootIntegrationTest {
    @Autowired
    private TestRestTemplate template;
}

Now, let’s add a test to make sure our public resources are available:

@Test
public void givenPublicResource_whenGetViaWeb_thenOk() {
    ResponseEntity<String> result = template.getForEntity("/hello/baeldung.txt", String.class);
    assertEquals("Hello From Baeldung", result.getBody());
}

We can also see what happens when we try to access one of our protected resources:

@Test
public void whenGetProtectedViaWeb_thenForbidden() {
    ResponseEntity<String> result = template.getForEntity("/protected", String.class);
    assertEquals(HttpStatus.FORBIDDEN, result.getStatusCode());
}

Here we get a FORBIDDEN response, as our anonymous request does not have the required role.

So, we can use this method to test our secured application, whichever security approach we choose.

5.2. Testing via Auto-Wiring and Annotations

Now let’s look at our second option. Let’s set up a @SpringBootTest and autowire our AnnotationSecuredController:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT)
public class GlobalMethodSpringBootIntegrationTest {
    @Autowired
    private AnnotationSecuredController api;
}

Let’s start by testing our publicly accessible method using @WithAnonymousUser:

@Test
@WithAnonymousUser
public void givenAnonymousUser_whenPublic_thenOk() {
    assertThat(api.publicHello()).isEqualTo(HELLO_PUBLIC);
}

Now that we’ve accessed our public resource, let’s use @WithMockUser annotations to access our protected methods.

First, let’s test our JSR-250 protected method with a user that has the “USER” role:

@WithMockUser(username="baeldung", roles = "USER")
@Test
public void givenUserWithRole_whenJsr250_thenOk() {
    assertThat(api.jsr250Hello()).isEqualTo("Hello Jsr250");
}

And now, let’s attempt to access the same method when our user doesn’t have the right role:

@WithMockUser(username="baeldung", roles = "NOT-USER")
@Test(expected = AccessDeniedException.class)
public void givenWrongRole_whenJsr250_thenAccessDenied() {
    api.jsr250Hello();
}

Our request was intercepted by Spring Security, and an AccessDeniedException was thrown.

We can only use this approach when we choose annotation-based security.

6. Annotation Cautions

When we choose the annotation-based approach, there are some important points to note.

Our annotated security only gets applied when we enter a class via a public method.

6.1. Indirect Method Invocation

Earlier, when we called an annotated method, we saw our security successfully applied. However, now let’s create a public method in the same class but without a security annotation. We’ll make it call our annotated jsr250Hello method:

@GetMapping("/indirect")
public String indirectHello() {
    return jsr250Hello();
}

Now let’s invoke our “/indirect” endpoint just using anonymous access:

@Test
@WithAnonymousUser
public void givenAnonymousUser_whenIndirectCall_thenNoSecurity() {
    assertThat(api.indirectHello()).isEqualTo(HELLO_JSR_250);
}

Our test passes as our  ‘secured’ method was invoked without triggering any security. In other words, no security is applied to the internal calls within the same class.

6.2. Indirect Method Invocation to a Different Class

Now let’s see what happens when our unprotected method invokes an annotated method on a different class.

First, let’s create a DifferentClass with an annotated method, differentJsr250Hello:

@Component
public class DifferentClass {
    @RolesAllowed("USER")
    public String differentJsr250Hello() {
        return "Hello Jsr250";
    }
}

Now, let’s autowire DifferentClass into our controller and add an unprotected differentClassHello public method to call it.

@Autowired
DifferentClass differentClass;

@GetMapping("/differentclass")
public String differentClassHello() {
    return differentClass.differentJsr250Hello();
}

And finally, let’s test the invocation and see that our security is enforced:

@Test(expected = AccessDeniedException.class)
@WithAnonymousUser
public void givenAnonymousUser_whenIndirectToDifferentClass_thenAccessDenied() {
    api.differentClassHello();
}

So, we see that although our security annotations won’t be respected when we call another method in the same class when we call an annotated method in a different class, then they are respected.

6.3. A Final Note of Caution

We should make sure that we configure our @EnableGlobalMethodSecurity correctly. If we don’t, then despite all of our security annotations, they could have no effect at all.

For example, if we’re using JSR-250 annotations but instead of jsr250Enabled=true we specify prePostEnabled=true, then our JSR-250 annotations will do nothing!

@EnableGlobalMethodSecurity(prePostEnabled = true)

We can, of course, declare that we will use more than one annotation type by adding them both to our @EnableGlobalMethodSecurity annotation:

@EnableGlobalMethodSecurity(jsr250Enabled = true, prePostEnabled = true)

7. When We Need More

Compared to JSR-250, we can also use Spring Method Security. This includes using the more powerful Spring Security Expression Language (SpEL) for more advanced authorization scenarios. We can enable SpEL on our EnableGlobalMethodSecurity annotation by setting prePostEnabled=true:

@EnableGlobalMethodSecurity(prePostEnabled = true)

In addition, when we want to enforce security based on whether a domain object is owned by the user, we can use Spring Security Access Control Lists.

We should also note that when we write reactive applications, we use @EnableWebFluxSecurity and @EnableReactiveMethodSecurity instead.

8. Conclusion

In this tutorial, we first looked at how to secure our application using a centralized security rules approach with @EnableWebSecurity.

Then, we built upon this by configuring our security to put those rules nearer to the code that they affect. We did this by using @EnableGlobalMethodSecurity and annotating the methods we wanted to secure.

Finally, we introduced an alternative way of relaxing security for public resources that don’t need it.

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)