Настройте Spring Boot для использования конвертера пользовательских токенов доступа - PullRequest
0 голосов
/ 10 февраля 2020

Я пытаюсь получить информацию о пользователе из токена доступа, предоставленного провайдером идентификации. Поставщик удостоверений, который я использую, предоставляет свою область видимости в виде строки вместо списка, из-за чего у меня не работает DefaultAccessTokenConverter. В результате я sh расширил его до CustomAccessTokenConverter, чтобы переопределить его метод extractAuthentication (). Я использую следующее в своей конфигурации безопасности, чтобы заставить Spring использовать этот пользовательский класс вместо класса по умолчанию:

@Configuration
@EnableResourceServer
public class SecurityConfig extends ResourceServerConfigurerAdapter {
    @Autowired
    private CustomAccessTokenConverter customAccessTokenConverter;

    // For validating the incoming access token and fetching user information from it
    @Bean
    public ResourceServerTokenServices createResourceServerTokenServices() {
        RemoteTokenServices tokenServices = new RemoteTokenServices();
        tokenServices.setCheckTokenEndpointUrl(*Introspection URL*);
        tokenServices.setClientId(*Client ID*);
        tokenServices.setClientSecret(*Client Secret*);
        return tokenServices;
    }

    @Bean
    public AccessTokenConverter accessTokenConverter() {
        return customAccessTokenConverter;
    }
}

Но Spring по-прежнему использует DefaultAccessTokenConverter. Что я делаю неправильно? Пожалуйста, помогите мне здесь.

Вот как выглядит мой класс CustomAccessTokenConverter просто для справки:

@Component
public class CustomAccessTokenConverter extends DefaultAccessTokenConverter {

    @Override
    public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
        .
        .
        .
        return new OAuth2Authentication(request, user);
    }
}

Я использую Spring Boot со следующими зависимостями:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security.oauth</groupId>
    <artifactId>spring-security-oauth2</artifactId>
    <version>2.0.9.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-oauth2-resource-server</artifactId>
    <version>5.2.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

1 Ответ

0 голосов
/ 10 февраля 2020

ResourceTokenServices позволяет нам использовать наш собственный AccessTokenConverter.

Просто добавьте следующее в вашу конфигурацию безопасности:

@Bean
public ResourceServerTokenServices createResourceServerTokenServices() {
    RemoteTokenServices tokenServices = new RemoteTokenServices();
    tokenServices.setCheckTokenEndpointUrl(*Introspection URL*);
    tokenServices.setClientId(*Client ID*);
    tokenServices.setClientSecret(*Client Secret*);
    // ADD THE NEXT LINE
    tokenServices.setAccessTokenConverter(customAccessTokenConverter);
    return tokenServices;
} 
...