Spring Webflux中资源服务器的范围不足

时间:2019-04-01 10:49:55

标签: java spring-boot oauth-2.0 spring-webflux

我无法在Spring Boot 2.1.3.RELEASE中设置使用Webflux的ResourceServer。用于身份验证的同一令牌可以在不使用Webflux的资源服务器上正常工作,如果我设置了.permitAll(),它也可以工作(显然)。这是我的资源服务器配置

授权服务器使用jwt令牌存储。

@EnableWebFluxSecurity
public class ResourceServerConfig {

  @Value("${security.oauth2.resource.jwt.key-value}")
  private String publicKey;
  @Autowired Environment env;
  @Bean
  SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) throws Exception {
    http
        .authorizeExchange()
        .pathMatchers("/availableInspections/**").hasRole("READ_PRIVILEGE")
        .anyExchange().authenticated()
        .and()
        .oauth2ResourceServer()
        .jwt()
        .jwtDecoder(reactiveJwtDecoder())
    ;
    return http.build();
  }

@Bean
public ReactiveJwtDecoder reactiveJwtDecoder() throws Exception{
    return new NimbusReactiveJwtDecoder(getPublicKeyFromString(publicKey));
  }

public static RSAPublicKey getPublicKeyFromString(String key) throws IOException, GeneralSecurityException {
    String publicKeyPEM = key;
    publicKeyPEM = publicKeyPEM.replace("-----BEGIN PUBLIC KEY-----\n", "");
    publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");
    byte[] encoded = Base64.getMimeDecoder().decode(publicKeyPEM);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(new X509EncodedKeySpec(encoded));
    return pubKey;
  }
}

我得到的错误是

WWW-Authenticate: Bearer error="insufficient_scope", error_description="The token provided has insufficient scope [read] for this request", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1", scope="read"

我已验证令牌具有必需的范围...

我需要更改/添加什么才能正确读取令牌?

2 个答案:

答案 0 :(得分:0)

Spring似乎仅在jwt令牌中添加scope下的内容,而忽略了authorities中的所有内容-因此除非我们将JwtAuthenticationConverter扩展为从令牌中的授权(或其他要求)。在安全配置中,我添加了jwtAuthenticationConverter

http
// path config like above
.oauth2ResourceServer()
.jwt()
.jwtDecoder(reactiveJwtDecoder())
.jwtAuthenticationConverter(converter())

并已覆盖JwtAuthenticationConverter以包括authorities个授予的权限:

public class MyJwtAuthenticationConverter extends JwtAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> {
    private static final String SCOPE_AUTHORITY_PREFIX = "SCOPE_";

    private static final Collection<String> WELL_KNOWN_SCOPE_ATTRIBUTE_NAMES =
            Arrays.asList("scope", "scp", "authorities"); // added authorities


    protected Collection<GrantedAuthority> extractAuthorities(Jwt jwt) {
        return this.getScopes(jwt)
                        .stream()
                        .map(authority -> SCOPE_AUTHORITY_PREFIX + authority)
                        .map(SimpleGrantedAuthority::new)
                        .collect(Collectors.toList());
    }

    private Collection<String> getScopes(Jwt jwt) {
      Collection<String> authorities = new ArrayList<>();
        // add to collection instead of returning early
        for ( String attributeName : WELL_KNOWN_SCOPE_ATTRIBUTE_NAMES ) {
            Object scopes = jwt.getClaims().get(attributeName);
            if (scopes instanceof String) {
                if (StringUtils.hasText((String) scopes)) {
                    authorities.addAll(Arrays.asList(((String) scopes).split(" ")));
                }
            } else if (scopes instanceof Collection) {
                authorities.addAll((Collection<String>) scopes);
            }
        }

        return authorities;
    }
}

答案 1 :(得分:0)

有点晚了,但是可能是一个更简单的解决方案(在kotlin中,但易于转换为java):

class CustomJwtAuthenticationConverter : Converter<Jwt, AbstractAuthenticationToken> {

  private val jwtGrantedAuthoritiesConverter = JwtGrantedAuthoritiesConverter()

  override fun convert(source: Jwt): AbstractAuthenticationToken {
    val scopes = jwtGrantedAuthoritiesConverter.convert(source)
    val authorities = source.getClaimAsStringList("authorities")?.map { SimpleGrantedAuthority(it) }
    return JwtAuthenticationToken(source, scopes.orEmpty() + authorities.orEmpty())
  }
}

,然后将实现提供给WebSecurityConfigurerAdapter,例如:

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
class ResourceServerConfig : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http {
            oauth2ResourceServer { 
                jwt { 
                    jwtDecoder = reactiveJwtDecoder()
                    jwtAuthenticationConverter = CustomJwtAuthenticationConverter() 
                } 
            }
        }
    }
}