Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add matchers to HttpSecurity spring web secure

Tags:

I try to implement spring security, but I have many roles and privileges, then I want to add the roles dynamically to each other resources. Like it:

@Override
protected void configure(HttpSecurity http) throws Exception {
    super.configure(http);


    //PageRequest p = new PageRequest(0, 1000);

    List<RolePrivilegeConfig> rolePrivilegesConfig=rolePrivilegeConfigService.findAll();

    for (RolePrivilegeConfig rolePrivilegeConfig : rolePrivilegesConfig) {

        http.authorizeRequests()
        .antMatchers("/login").permitAll()
        .antMatchers(rolePrivilegeConfig.getResource())
        .access(rolePrivilegeConfig.getRoleName())
        .anyRequest().authenticated();               
    } }

I have this error:

Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalStateException: Can't configure antMatchers after anyRequest.

How can I put all matchers and call request after?

like image 460
JhonArias Avatar asked Oct 16 '19 19:10

JhonArias


People also ask

How do I add security dependency in Spring?

For adding a Spring Boot Security to your Spring Boot application, we need to add the Spring Boot Starter Security dependency in our build configuration file. Maven users can add the following dependency in the pom. xml file. Gradle users can add the following dependency in the build.

What is Ant matchers 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.


1 Answers

@Override
protected void configure(HttpSecurity http) throws Exception {
    super.configure(http);


    //PageRequest p = new PageRequest(0, 1000);

    List<RolePrivilegeConfig> rolePrivilegesConfig=rolePrivilegeConfigService.findAll();

    http.authorizeRequests()
        .antMatchers("/login").permitAll();

    for (RolePrivilegeConfig rolePrivilegeConfig : rolePrivilegesConfig) {

        http.authorizeRequests()
        .antMatchers(rolePrivilegeConfig.getResource())
        .access(rolePrivilegeConfig.getRoleName());
    }

    http.authorizeRequests()
        .anyRequest().authenticated();
}
like image 110
Selindek Avatar answered Oct 12 '22 23:10

Selindek