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.

As always, the example code is available over on GitHub.