Обязательный компонент типа 'java .security.KeyPair' не найден - PullRequest
0 голосов
/ 17 февраля 2020

Я пытаюсь следовать весенней документации для OAUth2 Boot , чтобы реализовать AuthorizationServer и застрял на следующих элементах:

1.8.1 Настройка сервера авторизации для использования JWK и 1.8.2 Добавить конечную точку URI набора JWK

На основе описанной там информации я добавляю этот код в свой AuthorizationServerConfigurerAdapter:

@EnableAuthorizationServer
@Configuration
public class JwkSetConfiguration extends AuthorizationServerConfigurerAdapter {

    AuthenticationManager authenticationManager;
    KeyPair keyPair;

    public JwkSetConfiguration(AuthenticationConfiguration authenticationConfiguration,
            KeyPair keyPair) throws Exception {

        this.authenticationManager = authenticationConfiguration.getAuthenticationManager();
        this.keyPair = keyPair;
    }

    // ... client configuration, etc.

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        // @formatter:off
        endpoints
            .authenticationManager(this.authenticationManager)
            .accessTokenConverter(accessTokenConverter())
            .tokenStore(tokenStore());
        // @formatter:on
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setKeyPair(this.keyPair);
        return converter;
    }
}

и добавляю эти 2 класса в свой проект:

@FrameworkEndpoint
class JwkSetEndpoint {
    KeyPair keyPair;

    public JwkSetEndpoint(KeyPair keyPair) {
        this.keyPair = keyPair;
    }

    @GetMapping("/.well-known/jwks.json")
    @ResponseBody
    public Map<String, Object> getKey() {
        RSAPublicKey publicKey = (RSAPublicKey) this.keyPair.getPublic();
        RSAKey key = new RSAKey.Builder(publicKey).build();
        return new JWKSet(key).toJSONObject();
    }
}

и

@Configuration
class JwkSetEndpointConfiguration extends AuthorizationServerSecurityConfiguration {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http
            .requestMatchers()
                .mvcMatchers("/.well-known/jwks.json")
                .and()
            .authorizeRequests()
                .mvcMatchers("/.well-known/jwks.json").permitAll();
    }
}

все компилируется без ошибок, но когда я пытаюсь выполнить приложение, я получаю это сообщение:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 1 of constructor in oauth.server.Server required a bean of type 'java.security.KeyPair' that could not be found.

The injection point has the following annotations:
        - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'java.security.KeyPair' in your configuration.

Как я могу определить это ' Для запуска приложения требуется компонент java .security.KeyPair?

пс .: полный код моего AuthorizationServerConfigurerAdapter:

@Import(AuthorizationServerEndpointsConfiguration.class)
@Configuration
public class Server extends AuthorizationServerConfigurerAdapter {
    private AuthenticationManager authenticationManager;

    private KeyPair keyPair;

    public Server(AuthenticationConfiguration authenticationConfiguration, KeyPair keyPair) throws Exception {
        this.authenticationManager = authenticationConfiguration.getAuthenticationManager();
        this.keyPair = keyPair;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
            .inMemory()
                .withClient("first-client")
                .secret(passwordEncoder().encode("noonewilleverguess"))
                .scopes("resource:read")
                .authorizedGrantTypes("authorization_code")
                .redirectUris("http://localhost:8080/oauth/login/client-app");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
            .authenticationManager(this.authenticationManager)
            .accessTokenConverter(accessTokenConverter())
            .tokenStore(tokenStore());
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setKeyPair(this.keyPair);
        return converter;
    }
}

ОБНОВЛЕНИЕ

пом. xml

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth</groupId>
        <artifactId>spring-security-oauth2</artifactId>
        <version>2.4.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth.boot</groupId>
        <artifactId>spring-security-oauth2-autoconfigure</artifactId>
        <version>2.2.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-jwt</artifactId>
        <version>1.1.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>com.nimbusds</groupId>
        <artifactId>nimbus-jose-jwt</artifactId>
        <version>8.6</version>
    </dependency>
</dependencies>

1 Ответ

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

Мне удалось решить эту проблему, добавив этот компонент в мой класс Server:

@Autowired
private KeyPair keyPair;

@Bean
public KeyPair keyPairBean() throws NoSuchAlgorithmException {
  KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
  gen.initialize(2048);
  KeyPair keyPair = gen.generateKeyPair();
  return keyPair;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...