升级spring-security-web至5.6.9后出现Can't configure anyRequest after itself错误
问题原因
Spring Security 5.x版本强化了授权规则配置的校验逻辑,同一个authorizeRequests()配置链中只能调用一次anyRequest(),且不允许针对同一请求匹配器重复配置授权规则。你的代码里两次针对相同的端点路径,分别调用authorizeRequests().anyRequest().authenticated()和authorizeRequests().anyRequest().hasRole(...),触发了该校验异常。
解决方案
将重复的请求匹配器和授权规则合并,在同一个authorizeRequests()链中完成认证与角色校验的配置,无需拆分两次http配置。修改后的configure(HttpSecurity http)方法如下:
@Override protected void configure(HttpSecurity http) throws Exception { logger.info(String.format("provision.ldapGroupWithServiceAccess->%s", ldapGroupWithServiceAccess)); http.csrf().disable(); // Do not create sessions - authenticate user on every request http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); final String relativeProvisionEndpointPattern = VUserUris.ROOT + VUserUris.PROVISION; final String fullProvisionEndpointPattern = CommonUris.SERVLET_ROOT + relativeProvisionEndpointPattern; http .requestMatchers() .antMatchers(fullProvisionEndpointPattern + "/**", fullProvisionEndpointPattern + "*", relativeProvisionEndpointPattern + "/**", relativeProvisionEndpointPattern + "*") .and() .authorizeRequests() .anyRequest() .authenticated() // 要求用户已完成认证 .hasRole(ldapGroupWithServiceAccess) // 校验用户是否拥有指定LDAP角色 .and() .httpBasic() .and() .anonymous().disable(); }
补充说明
- 合并后的规则表示:匹配到指定端点的请求,必须同时满足已认证和拥有指定LDAP角色两个条件
- 若实际需求只需其中一个校验逻辑,可根据情况删除对应规则,但需保证
anyRequest()仅调用一次 - Spring Security授权规则按顺序匹配,
anyRequest()必须放在所有具体路径规则的最后,这一约束在新版本中仍需遵守
内容的提问来源于stack exchange,提问作者vishnu
相关产品推荐
相关产品推荐

