Spring Security Spring安全权限的表达式规则

7gcisfzg  于 2023-01-09  发布在  Spring
关注(0)|答案(1)|浏览(139)

我试图配置我的API并根据jwt的权限限制访问,我的权限格式如下:"角色_监视器|1 "或"角色监视器|2 "或"角色监视器|3 "等字符后的数字|'可以是任何数字。
我这样配置:

http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .and()
    .authorizeRequests()
    .antMatchers("/users").access("hasAuthority('^ROLE_MON\\|[0-9]+$')")
    .anyRequest().authenticated();

但不管用。
注意:如果没有正则表达式,则此操作有效,例如.antMatchers("/users").access("hasAuthority('ROLE_MON|1')")
适用于权限'ROLE_MON| 1'
我使用的是这个版本的springBoot:

plugins {
    id 'java'
    id 'org.springframework.boot' version '2.6.13'
    id 'io.spring.dependency-management' version '1.0.15.RELEASE'
}

我的依赖关系:

implementation(group: 'org.springframework.security.oauth', name: 'spring-security-oauth2', version: '2.5.2.RELEASE'){
    exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
}
implementation(group: 'org.springframework.security.oauth.boot', name: 'spring-security-oauth2-autoconfigure', version: '2.6.8'){
    exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
}
implementation(group: 'org.springframework.boot', name: 'spring-boot-starter-security'){
    exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
}
implementation(group: 'org.springframework.security', name: 'spring-security-jwt', version: '1.0.9.RELEASE'){
    exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
}

我试过:
antMatchers("/users").access("hasAuthority('^ROLE_MON.*')")
以及
antMatchers("/users").access("hasAuthority('^ROLE_MON.+')")
但是不起作用

fnx2tebb

fnx2tebb1#

使用默认RoleVoter无法执行此操作

Spring安全性只检查字符串是否相等,所以你不能在这里使用正则表达式。在你给出的例子中,你的令牌中的字符串^ROLE_MON.*^ROLE_MON.+是不存在的。有几种方法可以解决这个问题,最好的解决方案取决于你的需要。

编写自己的AccessDecisionVoter以提供正则表达式匹配:

你可以写一个可以接受正则表达式的custom AccessDecisionVoter,如果你不能枚举你现有的角色(可能是因为它们是动态生成的,或者因为它们太多了),这将是你唯一的最佳解决方案。

创建可用于向现有角色给予权限的一般角色:

如果你希望所有这些角色都能够访问此终结点,可以将它们添加到role hierarchy的一般角色下,以便每个ROLE_MON|.*都具有一般角色的权限。然后,可以将一般角色的名称添加到hasAuthority字符串,并使用该字符串配置对终结点的访问权限。只有在你可以合理地枚举要使用的角色时,才有可能实现这一点。

使用hasAnyAuthority和角色列表

此方法允许您提供角色列表,例如:

antMatchers("/users").access("hasAnyAuthority('ROLE_MON|1','ROLE_MON|2','ROLE_MON|3')")

如果角色的数量很小,这将是最简单的解决方案,并且不会很难维护,但可能会很难看或不可能,这取决于您有多少角色。

相关问题