通过Zuul网关访问路由时未识别用户角色与权限问题排查
我在Zuul Gateway微服务中为URL配置权限规则,由于所有端点均通过网关访问,因此我将权限规则部署在网关层。
客户端信息、令牌、角色、权限(authorities)均存储在数据库中。rolesauthoritiesADMIN角色拥有读写权限,USER角色仅拥有读权限。我使用管理员凭证在oauth/token端点生成令牌,随后调用oauth/check_token校验令牌,返回结果如下:
GET http://localhost:8765/authorization-service/oauth/check_token?token=f23e9fcc-1a85-43c4-8ef2-4efd00a7ccf5 { "active": true, "exp": 1604879905, "user_name": "gamofe", "authorities": [ "ROLE_ADMIN", "CAN_MANAGE", "CAN_READ" ], "client_id": "client", "scope": [ "READ", "WRITE" ] }
我在Zuul网关微服务中创建了继承WebSecurityConfigurerAdapter的@Configuration配置类,用于为路由应用权限规则:配置放行所有对authorization-service/**的访问,要求访问/user-service/api/v1/users/**的用户需拥有ADMIN或USER角色。
@Configuration @EnableWebSecurity public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter { public static final String USERS_URI = "/user-service/api/v1/users/**"; @Override protected void configure(HttpSecurity http) throws Exception { http .cors().and() .csrf().disable() .formLogin().disable() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .authorizeRequests() .antMatchers("/authorization-service/**").permitAll() .antMatchers(USERS_URI).hasAnyRole("ADMIN", "USER") .anyRequest().authenticated().and() .oauth2ResourceServer().opaqueToken(); } }
同时我在application.yml文件中配置了令牌内省地址:
spring: security: oauth2: resourceserver: opaquetoken: introspection-uri: 'http://localhost:8765/authorization-service/oauth/check_token' client-id: 'client' client-secret: 'pass'
当前配置下.anyRequest().authenticated()可以正常校验用户的认证状态,但完全忽略用户携带的权限与角色,访问受保护路由时始终返回403错误。
$ curl --location --request GET 'http://localhost:8765/user-service/api/v1/users' --header 'Authorization: Bearer f23e9fcc-1a85-43c4-8ef2-4efd00a7ccf5' {"timestamp":"2020-11-08T23:26:21.012+00:00","status":403,"error":"Forbidden","message":"Access Denied","path":"/user-service/api/v1/users"}%
我尝试过改用hasAuthority校验、多次调整端点配置,均未解决问题:移除hasAnyRole配置行后即可正常访问,网关完全无法读取用户令牌中携带的权限信息。暂未排查出其他问题,寻求排查思路。
问题根因
Spring Security 5.x 版本对不透明令牌(Opaque Token)的默认权限提取逻辑为:仅解析令牌内省返回的scope(或scp)字段生成权限,完全不会读取authorities字段的内容。
默认生成的权限格式为SCOPE_<scope值>,以示例中返回的scope: ["READ", "WRITE"]为例,最终只会生成SCOPE_READ、SCOPE_WRITE两个权限,认证对象中不存在ROLE_ADMIN、ROLE_USER这类从authorities字段提取的权限,hasAnyRole("ADMIN", "USER")校验自然无法通过,返回403。
补充说明:hasAnyRole方法本身会自动给传入的参数拼接ROLE_前缀,你配置的hasAnyRole("ADMIN", "USER")实际要求认证权限中存在ROLE_ADMIN或ROLE_USER,这部分逻辑没有问题,核心问题是权限没有被加载到认证对象中。
解决步骤
需要自定义不透明令牌的认证转换器,强制将内省返回的authorities字段转换为Spring Security可识别的GrantedAuthority对象,操作如下:
- 新建自定义转换器类,实现
OpaqueTokenAuthenticationConverter接口:
public class CustomOpaqueTokenAuthenticationConverter implements OpaqueTokenAuthenticationConverter { @Override public Authentication convert(String introspectedToken, OAuth2AuthenticatedPrincipal authenticatedPrincipal) { // 从内省返回的属性中提取authorities字段 Object authoritiesAttr = authenticatedPrincipal.getAttribute("authorities"); List<GrantedAuthority> authorities = new ArrayList<>(); if (authoritiesAttr instanceof Collection) { // 将authorities字段的每一项直接转为权限对象,无需额外加前缀 authorities = ((Collection<?>) authoritiesAttr).stream() .map(Object::toString) .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); } // 构造最终返回的认证对象 return new UsernamePasswordAuthenticationToken( authenticatedPrincipal, introspectedToken, authorities ); } }
- 修改原有安全配置类的
configure方法,将自定义转换器绑定到不透明令牌资源服务器配置上:
@Override protected void configure(HttpSecurity http) throws Exception { http .cors().and() .csrf().disable() .formLogin().disable() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .authorizeRequests() .antMatchers("/authorization-service/**").permitAll() .antMatchers(USERS_URI).hasAnyRole("ADMIN", "USER") .anyRequest().authenticated().and() .oauth2ResourceServer() .opaqueToken() // 绑定自定义的权限转换逻辑 .authenticationConverter(new CustomOpaqueTokenAuthenticationConverter()); }
- 效果验证:
自定义转换器加载后,内省返回的ROLE_ADMIN会直接作为权限存入认证对象,hasAnyRole("ADMIN")的校验逻辑可以正常匹配该权限。如果后续需要同时基于scope做权限校验,也可以在转换器中合并默认的scope权限提取逻辑,支持多维度权限控制。
额外注意点
- 如果使用
hasAuthority("ROLE_ADMIN")替换hasAnyRole("ADMIN"),权限匹配逻辑完全等价,无需额外修改 - 不要随意修改
hasAnyRole的前缀规则,除非确认所有权限都没有统一的ROLE_前缀,否则会导致权限匹配失效
内容的提问来源于stack exchange,提问作者user4383363

