Search code examples
javaspring-bootspring-security

What is the difference between restricting URLs based on Roles in the following two ways in spring security?


First way:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests()
            .requestMatchers(HttpMethod.GET, "/api/employees").hasRole("EMPLOYEE")
            .requestMatchers(HttpMethod.GET, "/api/employees/**").hasRole("EMPLOYEE")
            .requestMatchers(HttpMethod.POST, "/api/employees").hasRole("MANAGER")
            .requestMatchers(HttpMethod.PUT, "/api/employees").hasRole("MANAGER")
            .requestMatchers(HttpMethod.DELETE, "/api/employees/**").hasRole("ADMIN");
 
    http.httpBasic();
 
    http.csrf().disable();
 
    return http.build();
}

Second way:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests(configurer -> 
            configurer.requestMatchers(HttpMethod.GET, "/api/employees").hasRole("EMPLOYEE")
            .requestMatchers(HttpMethod.GET, "/api/employees/**").hasRole("EMPLOYEE")
            .requestMatchers(HttpMethod.POST, "/api/employees").hasRole("MANAGER")
            .requestMatchers(HttpMethod.PUT, "/api/employees").hasRole("MANAGER")
            .requestMatchers(HttpMethod.DELETE, "/api/employees/**").hasRole("ADMIN"));
 
    http.httpBasic();
 
    http.csrf().disable();
 
    return http.build();
}

I was trying to restrict access to Rest APIs based on Roles using Spring Security. I found there are two ways to do so. Both are working fine, but I want to know if there is a difference.


Solution

  • The second way, according to this article:

    It is a new approach to configure web security in Spring projects using lambda expressions. One of the main benefits of it is to avoid chaining using the and() method. It also promotes cleaner coding style in my opinion. Of course, the chaining style is still valid and the use of lambda expressions is optional.