Spring Security и авторизация через OAuth2 (Google) без Spring Boot

227
24 июня 2019, 05:50

Не могли бы вы посоветовать дельные статьи по прикручиванию гуглоавторизации? Дело в том, что везде все пишется только со Spring Boot, что не очень помогает разбору с нуля, так сказать. Пробовал использовать то, что есть в официальных доках, но оно выдает ошибку, о которой вообще информации ноль (могу рассказать поподробнее, если интересно), задавал по ней вопрос на английском стаковерфлоу - уже месяц без ответа.

По поводу ошибки.

  • Заходим на localhost:8080, появляется Login with OAuth 2.0 и список провайдеров.
  • Выбираем, например, Google (не существенно, результат один и тот же), редиректит на гугловскую страницу ввода логина и пароля, вводим их.
  • Редиректит на localhost:8080/login?error c сообщением:

    [invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response: Error while extracting response for type [class org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse] and content type [application/json;charset=utf-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: An error occurred reading the OAuth 2.0 Access Token Response: null; nested exception is java.lang.NullPointerException
    

Вот код:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {      
        http
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        .oauth2Login();
    }   
    @Bean   
    public ClientRegistrationRepository clientRegistrationRepository() {        
        List<ClientRegistration> clientRegistrations = new ArrayList<ClientRegistration>();     
        clientRegistrations.add(CommonOAuth2Provider.GOOGLE.getBuilder("google").clientId("id").clientSecret("secret").build());
        clientRegistrations.add(CommonOAuth2Provider.FACEBOOK.getBuilder("facebook").clientId("id").clientSecret("secret").build());            
        return new InMemoryClientRegistrationRepository(clientRegistrations);               
    }   
    @Bean
    public OAuth2AuthorizedClientService authorizedClientService(ClientRegistrationRepository clientRegistrationRepository) {
        return new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository);
    }
    @Bean
    public OAuth2AuthorizedClientRepository authorizedClientRepository(OAuth2AuthorizedClientService authorizedClientService) {
        return new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(authorizedClientService);
    }
}
public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer { }
@Configuration
@EnableWebMvc
@ComponentScan("com.solarward.auth")
public class WebConfiguration implements WebMvcConfigurer, ApplicationContextAware  {   
    private ApplicationContext applicationContext;  
    @Bean
    public SpringResourceTemplateResolver templateResolver() {      
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setApplicationContext(this.applicationContext);
        templateResolver.setPrefix("/WEB-INF/templates/");
        templateResolver.setSuffix(".html");        
        templateResolver.setTemplateMode(TemplateMode.HTML);        
        templateResolver.setCacheable(false);       
        return templateResolver;        
    }   
    @Bean
    public SpringTemplateEngine templateEngine() {      
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());     
        templateEngine.setEnableSpringELCompiler(true);
        return templateEngine;
    }
    @Bean
    public ThymeleafViewResolver viewResolver() {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine());
        return viewResolver;
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer  {
    @Override
    protected Class<?>[] getRootConfigClasses() {       
        return null;        
    }
    @Override
    protected Class<?>[] getServletConfigClasses() {        
        return new Class[] { WebConfiguration.class };      
    }
    @Override
    protected String[] getServletMappings() {       
        return new String[] { "/" };
    }
}
Answer 1

Решено! Всего-то не хватало зависимостей Jackson.

READ ALSO
Java Tomcat Listener повторная отправка запроса

Java Tomcat Listener повторная отправка запроса

Написал в томкате в webxml

175
Проблемы с VK API

Проблемы с VK API

Пишу програмку на джаве с использованием vk api, и проблема с методом messagessend

233
как в java проверить вводные данные на тип

как в java проверить вводные данные на тип

Подскажите новичку, как в java проверить вводные данные на тип? нужно получить вводные данные типа int, а не какие другиеСпасибо, заранее) P

190