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

Azure Spring Apps is a fully managed service from Microsoft (built in collaboration with VMware), focused on building and deploying Spring Boot applications on Azure Cloud without worrying about Kubernetes.

And, the Enterprise plan comes with some interesting features, such as commercial Spring runtime support, a 99.95% SLA and some deep discounts (up to 47%) when you are ready for production.

>> Learn more and deploy your first Spring Boot app to Azure.

You can also ask questions and leave feedback on the Azure Spring Apps GitHub page.

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:


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:


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.

public class MySecurityConfigurer {

3.1. A Quick Look at SecurityFilterChain Bean

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

public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.authorizeRequests((requests) -> requests.anyRequest().authenticated());

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())

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:

public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    return http.authorizeHttpRequests(request -> request.requestMatchers(new AntPathRequestMatcher("/admin/**"))
        .authorizeHttpRequests(request -> request.requestMatchers(new AntPathRequestMatcher("/protected/**"))

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:

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)
public class AnnotationSecuredController {
    public String adminHello() {
        return "Hello Admin";

    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) {

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

public class MyWebConfig {
    public WebSecurityCustomizer ignoreResources() {
        return (webSecurity) -> webSecurity

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:

@SpringBootTest(webEnvironment = RANDOM_PORT)
public class WebSecuritySpringBootIntegrationTest {
    private TestRestTemplate template;

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

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:

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:

@SpringBootTest(webEnvironment = RANDOM_PORT)
public class GlobalMethodSpringBootIntegrationTest {
    private AnnotationSecuredController api;

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

public void givenAnonymousUser_whenPublic_thenOk() {

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")
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() {

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:

public String indirectHello() {
    return jsr250Hello();

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

public void givenAnonymousUser_whenIndirectCall_thenNoSecurity() {

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:

public class DifferentClass {
    public String differentJsr250Hello() {
        return "Hello Jsr250";

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

DifferentClass 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)
public void givenAnonymousUser_whenIndirectToDifferentClass_thenAccessDenied() {

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.

Course – LSS (cat=Security/Spring Security)

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

res – Security (video) (cat=Security/Spring Security)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.