Spring Security中两种基于角色的URL权限控制方式有何差异?
Spring Security两种角色权限配置方式的差异分析
我在使用Spring Security基于角色限制Rest API访问权限时,发现两种均可正常运行的实现方式,想了解它们之间的差异。
第一种实现方式
@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(); }
第二种实现方式
@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(); }
两种方式的核心差异
这两种写法功能完全等价,本质都是配置Spring Security的请求授权规则,差异仅在于代码风格:
- 第一种是链式调用的传统写法:直接调用
http.authorizeHttpRequests()返回的AuthorizationManagerRequestMatcherRegistry对象,连续调用requestMatchers()方法完成配置。 - 第二种是Lambda表达式写法:利用Spring 5+引入的函数式配置接口,通过传入Lambda表达式对
AuthorizationManagerRequestMatcherRegistry进行配置,写法更简洁紧凑。
两种写法在底层逻辑、执行效果上没有任何区别,最终都会生成完全相同的安全过滤规则,选择哪种仅取决于个人或团队的代码风格偏好。
内容的提问来源于stack exchange,提问作者Mahmoud Reda
相关产品推荐
相关产品推荐

