Как я могу использовать curl для получения токена доступа для Spring Boot Rest API? - PullRequest
0 голосов
/ 14 марта 2019

Я занимаюсь разработкой API Spring Boot Rest с использованием аутентификации токена. Однако я не знаю, как получить токен доступа с помощью curl. Я разработал клиент для этого приложения, но не могу получить токен доступа с помощью клиента Spring.

Вот файл AuthorizationServerConfig.java:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private JwtAccessTokenConverter accessTokenConverter;


   @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void configure(ClientDetailsServiceConfigurer configurer) throws Exception{
        configurer
                .inMemory()
                .withClient(clientId)
                .secret(passwordEncoder.encode(clientSecret))
                .authorizedGrantTypes(grantType)
                .scopes(scopeRead,scopeWrite)
                .accessTokenValiditySeconds(1*60*60)
                .refreshTokenValiditySeconds(6*60*60)
                .resourceIds(resourceIds);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception{
        TokenEnhancerChain enhancerChain=new TokenEnhancerChain();
        enhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter));
        endpoints.tokenStore(tokenStore)
                .accessTokenConverter(accessTokenConverter)
                .tokenEnhancer(enhancerChain)
                .authenticationManager(authenticationManager);
    }
}

Вот файл ResourceServerConfig.java:

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Autowired
    private ResourceServerTokenServices tokenServices;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception{
        resources.resourceId(resourceIds).tokenServices(tokenServices);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception{
        http
                .requestMatchers()
                .and()
                .authorizeRequests()
                .antMatchers("/actuator/**","/api-docs/**").permitAll()
                .antMatchers("/data-service/**").authenticated();
    }

}

Вот файл WebSecurityConfig.java:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder(11);
        return bCryptPasswordEncoder;
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception{
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception{
        }

    @Override
    protected void configure(HttpSecurity http) throws Exception{

            http
                    .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                    .httpBasic()
                    .realmName(securityRealm)
                    .and()
                    .csrf()
                    .disable();

    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter(){
        JwtAccessTokenConverter converter=new JwtAccessTokenConverter();
        converter.setSigningKey(signingKey);
        return converter;
    }

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

    @Bean
    @Primary
    public DefaultTokenServices tokenServices(){
        DefaultTokenServices defaultTokenServices=new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setSupportRefreshToken(true);
        return defaultTokenServices;
    }
}

Как получить токен доступа с помощью curl?

1 Ответ

0 голосов
/ 15 марта 2019

Существуют разные типы грантов для получения токенов. Я бы предложил прочитать https://tools.ietf.org/html/rfc6749, чтобы лучше понять.

Следующая команда curl должна получить токен, используя учетные данные клиента тип предоставления. Вам необходимо передать заголовок Basic Authorization. Формат этого Basic base64 (Client_name: Client_secret)

curl -X POST http://localhost:8080/oauth/token -H 'authorization: Basic b2F1dGgyLWp3dC1jbGllbnQ6YWRtaW4xMjM0' -H 'content-type: multipart/form-data -F grant_type=client_credentials
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...