Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 461
Aliaksei Stadnik Avatar asked Apr 26 '19 07:04

Aliaksei Stadnik


People also ask

Which method defines the URL path that has to be secured?

The SecurityFilterChain bean defines which URL paths should be secured and which should not. Specifically, the / and /home paths are configured to not require any authentication.

What is anyRequest () authenticated ()?

anyRequest(). authenticated() is that any request must be authenticated otherwise my Spring app will return a 401 response.

Why is WebSecurityConfigurerAdapter deprecated?

0-M2 we deprecated the WebSecurityConfigurerAdapter , as we encourage users to move towards a component-based security configuration. To assist with the transition to this new style of configuration, we have compiled a list of common use-cases and the suggested alternatives going forward.


2 Answers

You can try this, d represent itemId

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

if you want to give permit all

antMatchers("/items/**").permitAll()
like image 103
Rowi Avatar answered Sep 28 '22 10:09

Rowi


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+]}")
like image 45
Jaspreet Jolly Avatar answered Sep 28 '22 11:09

Jaspreet Jolly