You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security中JWT权限正则匹配配置失效问题

解决Spring Security中使用正则匹配权限的问题

问题原因

hasAuthority()方法是精确匹配权限字符串,不支持直接传入正则表达式进行模糊匹配,所以你用hasAuthority("^ROLE_MON\\|[0-9]+$")的写法完全无法生效,只有指定具体权限值时才能匹配成功。

解决方案

方案1:使用SpEL表达式直接匹配正则

在Security配置中,改用access()方法结合Spring EL表达式,遍历当前用户的权限并做正则匹配:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/users")
                // Java字符串中反斜杠需双重转义,因此正则里的\|要写成\\\\|
                .access("authentication.authorities.stream().anyMatch(a -> a.authority.matches('^ROLE_MON\\\\|[0-9]+$'))")
                .anyRequest().authenticated()
                // 补充你的JWT过滤器等其他配置
                .and()
                .addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}

方案2:自定义权限检查组件

如果正则逻辑较复杂或需要多处复用,可以封装成自定义组件:

  1. 编写权限检查类
@Component("customAuthChecker")
public class CustomAuthChecker {
    public boolean hasMonRole(Authentication authentication) {
        return authentication.getAuthorities().stream()
                .anyMatch(auth -> auth.getAuthority().matches("^ROLE_MON\\|[0-9]+$"));
    }
}
  1. 在Security配置中引用该组件的方法
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/users")
            .access("@customAuthChecker.hasMonRole(authentication)")
            .anyRequest().authenticated()
            // 补充你的JWT过滤器等其他配置
            .and()
            .addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}

注意事项

  • 确保JWT解析后,权限字符串被正确注入到Authentication对象的authorities集合中,格式严格为ROLE_MON|数字,无多余空格或特殊字符。
  • 正则表达式可根据实际权限格式调整,比如数字允许多位、包含正负号等场景,需对应修改正则规则。

内容的提问来源于stack exchange,提问作者Igorov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 00:25:17