首页 > 解决方案 > Spring webflux oauth2 资源服务器自动配置身份验证转换器

问题描述

有人知道为什么我需要下面的代码线才能让它工作吗?

我认为它应该通过配置 Bean 自动应用?

.jwtAuthenticationConverter(reactiveJwtAuthenticationConverter()) //<-- 为什么我需要这条线???

@Configuration
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
@Import(LabcubeOAuth2SecurityConfiguration.class)
public class RestServiceOAuthConfig {
    @Bean
    SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        http.authorizeExchange()
                .pathMatchers("/api/v1/*/"+ ResourceType.SHARED.toString()).permitAll()
                .pathMatchers("/api/v1/**").hasAnyAuthority(LabcubeOAuth2SecurityConfiguration.ALL_ACCESS_SCOPE, LabcubeOAuth2SecurityConfiguration.ADMIN_ROLE, LabcubeOAuth2SecurityConfiguration.SUPPORT_ROLE)
                .pathMatchers("/api/**").authenticated()
                .and().oauth2ResourceServer().jwt()
                .jwtAuthenticationConverter(reactiveJwtAuthenticationConverter()) //<-- WHY DO I NEED THIS LINE???
        ;
        return http.build();
    }

    @Bean
    public ReactiveJwtAuthenticationConverter reactiveJwtAuthenticationConverter(){
        JwtGrantedAuthoritiesConverter grantedAuthoritiesConverterRoles = new JwtGrantedAuthoritiesConverter();
        grantedAuthoritiesConverterRoles.setAuthoritiesClaimName("role");
        grantedAuthoritiesConverterRoles.setAuthorityPrefix("");
        JwtGrantedAuthoritiesConverter grantedAuthoritiesConverterScopes = new JwtGrantedAuthoritiesConverter();
        grantedAuthoritiesConverterScopes.setAuthoritiesClaimName("scope");
        grantedAuthoritiesConverterScopes.setAuthorityPrefix("");

        ReactiveJwtAuthenticationConverter jwtAuthenticationConverter = new ReactiveJwtAuthenticationConverter();
        jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwt -> Flux.fromStream(Stream.concat(grantedAuthoritiesConverterRoles.convert(jwt).stream(), grantedAuthoritiesConverterScopes.convert(jwt).stream())));
        return jwtAuthenticationConverter;
    }
}

标签: springspring-oauth2webflux

解决方案


推荐阅读