I am studying some code of spring-security. I would like to understand this example that I found on internet 1:
http.requestMatchers()
.antMatchers("/management/**") // (1)
.and()
.authorizeRequests() // (2)
.antMatchers("/management/health")
.permitAll()
.antMatchers("/management/info")
.permitAll()
.antMatchers("/management/**")
.hasRole("ACTUATOR")
.anyRequest().permitAll()
.and()
.httpBasic(); (3)
}
I can not understand this configuration, why this code:
http.requestMatchers()
.antMatchers("/management/**")
.and()
Is before the .authorizeRequests() ? (1)
What does that mean?
Can you explanation this example?
2: In the second case, what is the difference?
http.requestMatchers().antMatchers("/rest2/**")
.and()
.authorizeRequests()
.antMatchers("/rest/v1/test/hello").permitAll()
.antMatchers("/rest/v1/test/**").denyAll()
.and()
.requestMatchers().antMatchers("/rest/**")
.and()
.authorizeRequests()
.antMatchers("/rest/v1/test/hello").permitAll();
What is the impact using requestMatchers()?
If I send a request to "/rest/v1/test/hello2" I received a 401 Why if the rule that deny a request does not match with the antMatchers("/rest2/**") ?
The purpose of requestMatchers()
is to specify which requests the spring security configuration will be applied to.
For example if you have 2 endpoints "/public"
and "/private"
and you only want security (specifically csrf protection) applied to "/private"
, then you could add the following configuration:
http
.requestMatchers()
.antMatchers("/private/**")
.and()
.csrf();
Then, if you POST to "/private"
you will get a 403 response.
But if you POST to "/public"
you will get a 200, because there has been no security applied.
This is separate from authorizeRequests
which indicates the type of access that is required for that endpoint, as opposed to whether security is applied at all.
In example 1 that you mention
http
.requestMatchers()
.antMatchers("/management/**")
.and()
...
the security configuration is only applied to "/management/**"
, so if you were to make a request to "/foo"
, it would not be secured.
In example 2 that you mention,
http
.requestMatchers()
.antMatchers("/rest2/**")
.and()
.authorizeRequests()
.antMatchers("/rest/v1/test/hello").permitAll()
.antMatchers("/rest/v1/test/**").denyAll()
.and()
.requestMatchers()
.antMatchers("/rest/**")
.and()
.authorizeRequests()
.antMatchers("/rest/v1/test/hello").permitAll();
the reason why "/rest/v1/test/hello2"
responds with a 401 is because "/rest/**"
is in a request matcher, so your security rule .antMatchers("/rest/v1/test/hello").permitAll()
will apply.
If you were to make a request to "/rest3/v1/test/hello2"
, then it would respond with a 200 because "/rest3/**"
is not part of any request matcher.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With