Поддельный пользователь в реактивном приложении весенней безопасности - PullRequest
1 голос
/ 10 февраля 2020

У меня есть приложение Spring, которое использует следующие зависимости:

<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.3.RELEASE</version>    

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-oauth2-jose</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>io.projectreactor</groupId>
        <artifactId>reactor-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.projectreactor</groupId>
        <artifactId>reactor-tools</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Приложение безопасности настроено следующим образом:

@Configuration
public class SecurityConfiguration {
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
    http.csrf().disable()
            .authorizeExchange()
            .pathMatchers("/**").hasAuthority("myAuthority")
            .anyExchange().authenticated()
            .and()
            .oauth2ResourceServer()
            .jwt()
            .jwtAuthenticationConverter(converter());
    return http.build();
}

@Bean
public Converter<Jwt, Mono<AbstractAuthenticationToken>> converter() {
    JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
    jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(new GrantedAuthoritiesExtractor());
    return new ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter);
}

static class GrantedAuthoritiesExtractor implements Converter<Jwt, Collection<GrantedAuthority>> {

    public Collection<GrantedAuthority> convert(Jwt jwt) {
        Collection<String> authorities = (Collection<String>) jwt.getClaims().get("roles");

        if(authorities == null) {
            authorities = List.of();
        }
        return authorities.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }
}

}

, поэтому мне нужно аутентифицированный пользователь запрашивает API и полномочия myAuthority.

Я хотел бы написать несколько тестов для этого, чтобы убедиться, что тест не пройден, если кто-то изменит конфигурацию безопасности. Я использую это:

    protected WebTestClient webTestClient(Object controller) {
    return WebTestClient.bindToController(controller)
            .apply(springSecurity())
            .configureClient()
            .build()
            .mutateWith(mockJwt().authorities(new SecurityConfiguration.GrantedAuthoritiesExtractor()));
}

, но все тесты пройдены, и ни аутентифицированный пользователь не требуется, ни полномочия.
Я хотел бы использовать @MockUser для проверки ролей.

РЕДАКТИРОВАТЬ для получения дополнительной информации о тестах

вот тестовый класс

@ExtendWith(SpringExtension.class)
@WebFluxTest(controllers = MyController.class)
@Import({MyRepository.class, ValidationConfiguration.class})
public class MyControllerTest extends BaseControllerTest {

    @Autowired
    MyController controller;

    @Test
    public void test() {}

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...