Spring Security Securing Endpoints Using antMatchers() (original) (raw)

Last Updated : 22 May, 2026

Spring Security provides security features for Java web applications by handling authentication and authorization. One of the commonly used methods in Spring Security 5 is antMatchers(), which helps secure endpoints based on roles, authorities, or authentication status.

How antMatchers() Works

The mapping rules in antMatchers() support special characters for flexible matching

**Examples:

Methods applied on antmatchers()

Implementation of Securing Endpoints Using antMatchers()

Step 1: Create Spring MVC Project and Configure Tomcat

Before moving to the project let’s have a look at the complete project structure for our Spring MVC application.

File-Strcture.png

Folder Structure

Step 2: Add Dependencies to pom.xml File

Add the following dependencies to your pom.xml file

**pom.xml:

XML `

4.0.0

com.gfg.springsecurity springsecurity 0.0.1-SNAPSHOT war

springsecurity Maven Webapp http://www.gfg.com

UTF-8 1.7 1.7
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.24</version>
</dependency>

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
</dependency>    

<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>5.7.3</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-web -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
    <version>5.7.3</version>
</dependency>
springsecurity maven-clean-plugin 3.1.0 maven-resources-plugin 3.0.2 maven-compiler-plugin 3.8.0 maven-surefire-plugin 2.22.1 maven-war-plugin 3.2.2 maven-install-plugin 2.5.2 maven-deploy-plugin 2.8.2

`

Step 3: Configuring Dispatcher Servlet

Go to the src > main > java and create a class WebAppInitilizer.

**WebAppInitilizer.java

Java `

package com.gfg.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebAppInitilizer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
    // TODO Auto-generated method stub
    return null;
}

@Override
protected Class<?>[] getServletConfigClasses() {
    Class[] configFiles = {MyAppConfig.class};
    return configFiles;
}

@Override
protected String[] getServletMappings() {
    String[] mappings = {"/"};
    return mappings;
}

}

`

Step 4: Configure Spring MVC

Create another class in the same location (src > main > java) and name it MyAppConfig.

**MyAppConfig.java

Java `

package com.gfg.config;

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration @EnableWebMvc @ComponentScan("com") public class MyAppConfig {

@Bean
InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".jsp");
    return resolver;
}

}

`

Step 5: Create Spring MVC Controller

Go to the src > main > java and create a class GfgController.

**GfgController.java

Java `

package com.gfg.controller;

import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody;

@Controller public class GfgController {

// Secure this one
@GetMapping("/gfg")
public String helloGfg() {
    return "hello-gfg";
}

// Don't secure this
@GetMapping("/gfg/welcome")
@ResponseBody
public String welcomeGfg() {
    return "Welcome to GeeksforGeeks";
}

}

`

Step 6: Create View

Go to the src > main > webapp > WEB-INF > right-click > New > Folder and name the folder as views. Then views > right-click > New > JSP File.

Hello GeeksforGeeks!

`

Step 7: Setup Spring Security

Go to the src > main > java and create a class SecurityInitializer.

**SecurityInitializer.java

Java `

package com.gfg.config;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

// This class will help to register spring security filter chain with our application public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {

}

`

Step 8: Configure Spring Security Using antMatchers()

Configure spring security: Go to the src > main > java and create a class MySecurityAppConfig.

**MyAppConfig.java

Java `

package com.gfg.config;

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.password.PasswordEncoder;

@SuppressWarnings("deprecation") @EnableWebSecurity public class MySecurityAppConfig extends WebSecurityConfigurerAdapter {

@Autowired
private PasswordEncoder passwordEncoder;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
        .withUser("gfg")
        .password(passwordEncoder.encode("gfg123"))
        .roles("admin");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests()
        .antMatchers("/gfg").authenticated()
        .antMatchers("/gfg/welcome").permitAll()
        .and()
        .formLogin().loginPage("/customLogin")
        .and()
        .httpBasic();
}

}

`

Step 9: Run the Application

To run our Spring MVC Application right-click on your project > Run As > Run on Server. After that use the following URL to run your controller.

http://localhost:8080/springsecurity/gfg

And it will ask for authentication to use the endpoint and a pop-up screen will be shown like this.

Now sign in with the following credentials

And now you can access your endpoint. You will get the output like this.

But when you hit the following endpoint you can access it without any authentication.

http://localhost:8080/springsecurity/gfg/welcome

You will get the output like this.

antmatcher-1.png