When to use Spring Security`s antMatcher()? - spring-mvc

When do we use antMatcher() vs antMatchers()?
For example:
http
.antMatcher("/high_level_url_A/**")
.authorizeRequests()
.antMatchers("/high_level_url_A/sub_level_1").hasRole('USER')
.antMatchers("/high_level_url_A/sub_level_2").hasRole('USER2')
.somethingElse()
.anyRequest().authenticated()
.and()
.antMatcher("/high_level_url_B/**")
.authorizeRequests()
.antMatchers("/high_level_url_B/sub_level_1").permitAll()
.antMatchers("/high_level_url_B/sub_level_2").hasRole('USER3')
.somethingElse()
.anyRequest().authenticated()
.and()
...
What I expect here is,
Any request matches to /high_level_url_A/** should be authenticated + /high_level_url_A/sub_level_1 only for USER and /high_level_url_A/sub_level_2 only for USER2
Any request matches to /high_level_url_B/** should be authenticated + /high_level_url_B/sub_level_1 for public access and /high_level_url_A/sub_level_2 only for USER3.
Any other pattern I don't care - But should be public ?
I have seen latest examples do not include antMatcher() these days. Why is that? Is antMatcher() no longer required?

You need antMatcher for multiple HttpSecurity, see Spring Security Reference:
5.7 Multiple HttpSecurity
We can configure multiple HttpSecurity instances just as we can have multiple <http> blocks. The key is to extend the WebSecurityConfigurationAdapter multiple times. For example, the following is an example of having a different configuration for URL’s that start with /api/.
#EnableWebSecurity
public class MultiHttpSecurityConfig {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) { 1
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER", "ADMIN");
}
#Configuration
#Order(1) 2
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/**") 3
.authorizeRequests()
.anyRequest().hasRole("ADMIN")
.and()
.httpBasic();
}
}
#Configuration 4
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin();
}
}
}
1 Configure Authentication as normal
2 Create an instance of WebSecurityConfigurerAdapter that contains #Order to specify which WebSecurityConfigurerAdapter should be considered first.
3 The http.antMatcher states that this HttpSecurity will only be applicable to URLs that start with /api/
4 Create another instance of WebSecurityConfigurerAdapter. If the URL does not start with /api/ this configuration will be used. This configuration is considered after ApiWebSecurityConfigurationAdapter since it has an #Order value after 1 (no #Order defaults to last).
In your case you need no antMatcher, because you have only one configuration. Your modified code:
http
.authorizeRequests()
.antMatchers("/high_level_url_A/sub_level_1").hasRole('USER')
.antMatchers("/high_level_url_A/sub_level_2").hasRole('USER2')
.somethingElse() // for /high_level_url_A/**
.antMatchers("/high_level_url_A/**").authenticated()
.antMatchers("/high_level_url_B/sub_level_1").permitAll()
.antMatchers("/high_level_url_B/sub_level_2").hasRole('USER3')
.somethingElse() // for /high_level_url_B/**
.antMatchers("/high_level_url_B/**").authenticated()
.anyRequest().permitAll()

I'm updating my answer...
antMatcher() is a method of HttpSecurity, it doesn't have anything to do with authorizeRequests(). Basically, http.antMatcher() tells Spring to only configure HttpSecurity if the path matches this pattern.
The authorizeRequests().antMatchers() is then used to apply authorization to one or more paths you specify in antMatchers(). Such as permitAll() or hasRole('USER3'). These only get applied if the first http.antMatcher() is matched.

Related

Spring Actuator, not able to expose even after trying somany options

I'm trying to explore the Spring actuator endpoints through springboot project. I'm unable to expose any of the endpoints. It always shows the 'Exposing 1 endpoint(s) beneath base path '/actuator' in log. Below is my dependency details added in build.gradle and application.yml file. I have used spring security as well, to expose the endpoint only to user with certain role. But still nothing works. Requesting suggestions.
build.gradle:
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
I'm using Spring boot version 2.6.6
application.yml
management:
endpoint:
health:
show-details: always
endpoints:
web:
exposure:
include: health
Spring Security :
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/actuator/**").hasAnyAuthority("ADMIN")
.anyRequest().permitAll()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
http.csrf().disable().headers().frameOptions().disable();
}
}
The issue was with the application.yml. The management.endpoint.web.exposure.health was added below the Spring entry. The actuator entry needed to be added above that.

Spring boot application not able to access rest path

I am trying to set up the rules for spring boot to allow/deny access for specific paths. I looked up various examples and stack overflow question, but none was helpful. I created the configuration file as follows:
package xyz.blackmonster.window.configs;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
#EnableWebSecurity
#Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
#Value("${admin.console.username:admin}")
private String username;
#Value("${admin.console.password:admin}")
private String password;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser(username)
.password(passwordEncoder().encode(password)).roles("ADMIN");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/assets/**", "/api/order/calculate", "/api/order/**").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/login.html")
.defaultSuccessUrl("/admin/orders.html")
.failureUrl("/login.html?error=true")
.and()
.logout().logoutSuccessUrl("/");
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
I can access the "/" without a problem. The page is loaded and show with the help of the MVC controller. But the paths that I defined as REST end points, I am not able to access them. I keep getting a 403 response:
{"timestamp":"2018-10-08T19:22:04.963+0000","status":403,"error":"Forbidden","message":"Forbidden","path":"/api/order/calculate"}
What is wrong with my configuration? As you can see from the class, I even went one further and specifically set the calculate end point as oppose to having the ** to include all subpaths.
If "/" is working and "/api/order/calculate" is not, it means that they have different HTTP verbs.
"/" - is a GET request
"/api/order/calculate" - is a POST request
By default, spring security will enable csrf protection (only for POST because GET is considered safe). If you are getting 403, it means that you are not sending csrf header => your access is forbidden.
You said that this is a REST endpoint, so you should disable csrf for this endpoints. To do that, please update your configuration with:
1.disable csrf in general (not recommended if you have web forms)
http.csrf()
.disable();
2.if you need to ignore csrf only for specific endpoints, you can add:
http.csrf()
.ignoringAntMatchers("/api/order/calculate")

hasAuthority method for only POST and PUT httpmethods

Here is my configure code snippet
#Override
public void configure(HttpSecurity http) throws Exception {
http.
authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/api/user/**").hasAnyAuthority("ROLE_ADMIN")
.antMatchers("/api/status/**").hasAuthority("ROLE_ADMIN").anyRequest()
.authenticated()
.and()
.exceptionHandling()
.accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
In this I need to make ROLE_ADMIN to access only POST and PUT httpmethods. He should not be able to access GET or DELETE httpmethod. I need this to be done in a single .antMatchers() method.
How can I do this?
Have a look at this Spring example project. You can define matchers per path and HTTP verb.
http
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/employees").hasRole("ADMIN")
.antMatchers(HttpMethod.PUT, "/employees/**").hasRole("ADMIN")
.antMatchers(HttpMethod.PATCH, "/employees/**").hasRole("ADMIN")

why spring security makes spring mvc 's postmapping controllder do not work

when I config spring security like this
#EnableWebSecurity
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{
#Bean
public UserDetailsService userDetailsService(){
return new MyUserDetailsService();
}
#Bean
public MyAuthenticationProvider myAuthenticationProvider(){
MyAuthenticationProvider provider = new MyAuthenticationProvider();
provider.setUserDetailsService(userDetailsService());
return provider;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// TODO Auto-generated method stub
http
.csrf()
.disable()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll();
}
}
and then I config my controller like this
#GetMapping("/login")
public String showLoginPage(){
System.out.println("GetMapping");
return "login";
}
#PostMapping("/login")
public void authUser(#RequestParam String username,#RequestParam String password){
// just for testing
System.out.println("PostMapping");
}
and then I visit my login page and enter my username and password, but the console doesn't print "PostMapping", which means the program doesn't go into my method "authUser" with #PostMapping.
Though my program runs successfully, but it makes me quite confuse.I suppose spring security doing some work automatically, but now I have no idea where to add my Authentications to the SecurityContextHolder.
I hope somebody can help and thanks very much
It has done by UsernamePasswordAuthenticationFilter, and the default processing path is Post /login, and the Authentication already exist in SecurityContextHolder, you can get it in controller.
If you want to disable form login, change to this.
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated().and()
.formLogin().disable();
Normally, POST mappings are filtered by CSRFfilters. Although it is not recommended in the production environment, you can disable CSRF filter simply using for learning cases:
http.authorizeRequests().anyRequest().authenticated().and().httpBasic()
.and().logout()
.and().csrf().disable();

Spring MVC 4 Global Basic HTTP Authentication

I need to set up global basic HTTP authentication for a staging server. Nothing fancy. I just want to require username/password to access anything. I also would like to use only Java config. I've experimented with a lot of different solutions, but none of them working. I'm always able to access all resources on the server. This is what I'm doing now:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
System.out.println("Configuring HttpSecurity");
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
System.out.println("Configuring global AuthenticationManagerBuilder");
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
I can see in the logs that these snippets are being executed. As you can see, in the first method, I am requiring that all requests are authenticated. In the second method, I am specifying in memory authentication.
Your SOP statements are getting printed (while container instantiation) because of #Configuration (which is again not required as it is also declared by #EnableWebSecurity). You still need to register the spring security filter chain in your web.xml or MVC initializer class that extends WebMvcConfigurerAdapter or implements WebApplicationInitializer if you wish to use it with the application filter chain. For example (java config as you are looking for the same):
EnumSet<DispatcherType> dispatcherTypes = EnumSet.of(
DispatcherType.REQUEST, DispatcherType.ERROR);
container.addFilter("springSecurityFilterChain",
DelegatingFilterProxy.class).addMappingForUrlPatterns(
dispatcherTypes, false, "/*");
where container is an instance of ServletContext.

Resources