'How to apply Spring Security AntMatchers pattern only to url with pathVariable
I am using Spring boot and WebSecurityConfigurerAdapter to configure security.
Method to configure ignored security antMatches looks like this:
@Override
public void configure(final WebSecurity web) {
web
.ignoring()
.antMatchers("/items")
.antMatchers("/items/{itemId}")
where {itemId} is in UUID format
The issues is that with this configuration endpoints like/items/report, /items/images are also opened, but they should not.
Is there a way to apply ignoring rule only to uri with path variables ?
Solution 1:[1]
You can try this, d represent itemId
antMatchers("/items/{\\d+}").access("hasAnyAuthority('ROLE')")
if you want to give permit all
antMatchers("/items/**").permitAll()
Solution 2:[2]
According to the documentation for AntPathMarcher, you need to specify the path variable with the regex as per doc:
{spring:[a-z]+} matches the regexp [a-z]+ as a path variable named "spring".
In your case it will be:
@Override
public void configure(final WebSecurity web) {
web
.ignoring()
.antMatchers("/items/{itemId:[\\d+]}")
Solution 3:[3]
For more sophisticated matching, than an Ant pattern can do, use method based security on your controller or (better) service layer methods.
Solution 4:[4]
You can use @preAuthorize annotation on the handler method for that url in the controller or check out this link https://docs.spring.io/spring-security/site/docs/4.2.x/reference/html/el-access.html
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | howie |
| Solution 2 | dur |
| Solution 3 | Raedwald |
| Solution 4 | Abd Qadr |
