升级到authorizeHttpRequests后,如何正确配置expressionHandler?
在Spring Security 6.x版本中,authorizeHttpRequests()返回的AuthorizationManagerRequestMatcherRegistry不再提供expressionHandler()方法,这是API重构导致的差异,替代方案有两种:
方案1:全局配置自定义表达式处理器
直接在HttpSecurity级别设置表达式处理器,而非在authorizeHttpRequests()的返回对象上调用:
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // 你的自定义表达式处理器实例 CustomSecurityExpressionHandler expressionHandler = new CustomSecurityExpressionHandler(); http .authorizeHttpRequests(auth -> auth // 配置你的权限规则,例如 .requestMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() ) // 全局设置表达式处理器 .expressionHandler(expressionHandler); return http.build(); }
方案2:针对特定规则使用自定义表达式处理器
如果仅需部分权限规则使用自定义处理器,可以创建基于表达式的AuthorizationManager:
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { CustomSecurityExpressionHandler expressionHandler = new CustomSecurityExpressionHandler(); // 创建基于表达式的权限管理器 AuthorizationManager<RequestAuthorizationContext> customAuthManager = RequestAuthorizationContextAuthorizationManager.createWithExpressionHandler( expressionHandler, "hasCustomPermission(request, authentication)" ); http .authorizeHttpRequests(auth -> auth .requestMatchers("/custom/**").access(customAuthManager) .anyRequest().authenticated() ); return http.build(); }
核心变化:Spring Security 6+重构了权限授权的API,将表达式处理器的配置提升到全局HttpSecurity层面,或通过AuthorizationManager实现细粒度控制,替代了旧版本中authorizeRequests()下直接绑定处理器的方式。
内容的提问来源于stack exchange,提问作者Trickery
相关产品推荐
相关产品推荐

