Spring boot oAuth2 «Bad Credentials» после успешного входа - PullRequest
0 голосов
/ 14 сентября 2018

Я пытаюсь защитить REST API в моем приложении Spring Boot по стандарту oAuth2.Я создал классы, расширяющие AuthorizationServerConfigurerAdapter, ResourceServerConfigurerAdapter и WebSecurityConfigurerAdapter, и, к сожалению, он работает только со сценарием входа в систему.Запрос / oauth / token возвращает access_token и т. д., но в любом другом случае я получаю 401, Несанкционированные, Плохие учетные данные.Я думал, что неправильный cliendId / secret имеет место, но это также повлияет на вход в систему, верно?PS Приложение подключено к базе данных MySql.

У меня уже закончились идеи, поэтому, возможно, вы, ребята, сможете мне помочь.

WebSecurityConfig.java:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    public void configureGlobal(final AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/oauth/token").permitAll()
                .anyRequest().authenticated()
                .and()
                .httpBasic()
                .and()
                .csrf().disable();
    }

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

}

AuthorizationServerConfig.java:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()")
                .allowFormAuthenticationForClients();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("client")
                .authorizedGrantTypes("client-credentials", "password","refresh_token")
                .authorities("ROLE_CLIENT", "ROLE_ANDROID_CLIENT")
                .scopes("read", "write", "trust")
                .resourceIds("oauth2-resource")
                .accessTokenValiditySeconds(5000)
                .secret("secret")
                .refreshTokenValiditySeconds(50000);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
    }
}

ResourceServerConfig.java:

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/api/**").authenticated();
    }
}

MainApplication.java:

@SpringBootApplication
@ComponentScan({"com.user.app"})
public class MainApplication {

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }

    @Autowired
    public void authenticationManaget(AuthenticationManagerBuilder builder, UserRepository repository) throws Exception {
        builder.userDetailsService(new UserDetailsServiceImpl());
    }

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

1 Ответ

0 голосов
/ 20 сентября 2018

Хорошо, в некоторых местах конфигурация oAuth2 была перезаписана базовой конфигурацией.Эти места все еще не были защищены oAuth, поэтому ошибка «Bad Credentials» возникала даже после предоставления правильного токена доступа.Комментирование метода configure () внутри WebSecurityConfig решило проблему.

...