Spring GateWay OAuth2ResourceServer 配置ServerHttpSecurity中的hasRole 无效的问题


文章原地址

问题

当gateway充当OAuth2ResourceServer的时候,会出现hasRole配置无效的问题。

原因来自于ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec中默认的ReactiveAuthenticationManager没有将jwt中authorities 的负载部分当做Authentication的权限。

简而言之,我们需要把jwt 的Claim中authorities的值加入 这里有个人提出了这个问题,但是官方认为仅仅使用scope``scp这两个字段当做权限就足够了github issue

解决方案

我们重新定义一个ReactiveAuthenticationManager权限管理器 默认的权限管理器使用jwtGrantedAuthoritiesConverter作为默认的转换器,就是这个转换器默认只读取"scope", "scp"这两个作为权限。

JwtGrantedAuthoritiesConverter源码

来看源码,源码不长。
convert方法可以理解为转换器的调用入口,从这个方法开始看

/**
 * Extracts the {@link GrantedAuthority}s from scope attributes typically found in a
 * {@link Jwt}.
 *
 * @author Eric Deandrea
 * @since 5.2
 */
public final class JwtGrantedAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> {
	private static final String DEFAULT_AUTHORITY_PREFIX = "SCOPE_";

	private static final Collection<String> WELL_KNOWN_AUTHORITIES_CLAIM_NAMES =
			Arrays.asList("scope", "scp");

	private String authorityPrefix = DEFAULT_AUTHORITY_PREFIX;

	private String authoritiesClaimName;

	/**
	 * Extract {@link GrantedAuthority}s from the given {@link Jwt}.
	 *
	 * @param jwt The {@link Jwt} token
	 * @return The {@link GrantedAuthority authorities} read from the token scope
  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值