Aliaksei Stadnik
Aliaksei Stadnik

Reputation: 1948

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 ?

Upvotes: 17

Views: 16785

Answers (4)

Jaspreet Jolly
Jaspreet Jolly

Reputation: 1313

According to the documentation for AntPathMatcher, you need to specify the path variable with the regex as per documentation:

{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+]}")

Upvotes: 2

Abd Qadr
Abd Qadr

Reputation: 63

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

Upvotes: -1

Rowi
Rowi

Reputation: 565

You can try this, d represent itemId

antMatchers("/items/{\\d+}").access("hasAnyAuthority('ROLE')")

if you want to give permit all

antMatchers("/items/**").permitAll()

Upvotes: 4

Raedwald
Raedwald

Reputation: 48674

For more sophisticated matching, than an Ant pattern can do, use method based security on your controller or (better) service layer methods.

Upvotes: 0

Related Questions