Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

antMatchers Spring Security pattern with changeable URL user ID

I was looking for the answer for a long time but couldnt find anything productive

In my rest service I keep some functionality under: /account/{id}/download and I would like to set the acces ROLE in SecurityConfig java file, that only ROLE_TOKENSAVED users can access this url

How should the pattern look like, when {id} is changeable?

I tried some regexp patterns, but nothing worked as I wanted, here are some of my attempts:

1. antMatchers("account/**/download").access(somerolehere) 2. antMatchers("account/\\d/download").access(somerolehere) 3. antMatchers("account/[\\d]/download").access(somerolehere) 

thanks in advance for your anserwers :)

edit:

    @Override     protected void configure(HttpSecurity http) throws Exception {                     http.authorizeRequests()                 .antMatchers("/admin**").access("hasRole('ROLE_ADMIN')")                 .antMatchers("/account*//**").access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")                 .antMatchers("/account/\\d+/download").access("hasRole('ROLE_TOKENSAVED')")                 .antMatchers("/user**").permitAll()                 //othercode...     } 
like image 220
azalut Avatar asked Dec 25 '14 18:12

azalut


People also ask

How do I enable Spring Security for a specific URL?

authenticated(): This is the URL you want to protect, and requires the user to login. permitAll(): This is used for URL's with no security applied for example css, javascript. hasRole(String role): Restrict to single role. Note that the role will have “ROLE_” appended.

What does antMatchers do in Spring Security?

The antMatchers() is a Springboot HTTP method used to configure the URL paths from which the Springboot application security should permit requests based on the user's roles. The antmatchers() method is an overloaded method that receives both the HTTP request methods and the specific URLs as its arguments.

How do I disable Spring Security for a specific URL?

antMatchers("/api/v1/signup"). permitAll().

What is hasRole and hasAnyRole?

hasRole, hasAnyRole. These expressions are responsible for defining the access control or authorization to specific URLs and methods in our application: @Override protected void configure(final HttpSecurity http) throws Exception { ... . antMatchers("/auth/admin/*").


1 Answers

This works for me:

antMatchers("/account/{\\d+}/download").access("hasAnyAuthority('ROLE_TOKENSAVED')") 

Notice the curly braces around the path variable representing the ID.

like image 120
Bohuslav Burghardt Avatar answered Sep 27 '22 22:09

Bohuslav Burghardt