Home > Back-end >  Springboot hasAnyRole allow all/any roles
Springboot hasAnyRole allow all/any roles

Time:07-18

I have an endpoint that I have to expose to all roles, whoever has at least one of the roles should get access to the api.

    @PreAuthorize("hasAnyRole('ADMIN', 'USER')")

Now that the number of roles is increasing i have to add all the new roles to the API. Is there any way to expose everyone who have any role without specifying everyrole here? I am expecting something like this

   @PreAuthorize("hasAnyValidRole()")

CodePudding user response:

We can directly do it from WebSecurityConfigurerAdapter, override the method protected void configure(HttpSecurity http) and don't use PreAuthorize annotation

you may simple write

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ApiSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
           http.antMatcher("your end point here").authorizeRequests().anyRequest().authenticated();
    }

}

this will allow any authenticated user to access that URL

Hope this Helps !

CodePudding user response:

Finally got a quite easy solution.

@PreAuthorize("isAuthenticated()")
  • Related