3

Всем привет!

Пытаюсь реализовать авторизацию на сайте через социальные сети такие как VK, OK, Google, Facebook в Spring Security.

C google авторизация работает, а вот через VK нет. Авторизация проходит успешно, но на этапе получения токена вылетает ошибка, причем в отладчике я её не вижу.

Ниже лог запросов:

  1. запрос на получения кода авторизации

https://login.vk.com/?act=grant_access&client_id=123456&settings=43434&redirect_uri=http%3A%2F%2Fxxxx.ru%2Fapi%2Foauth2%2Fcallback%2Fvk&response_type=code&group_ids=&token_type=0&v=5.95&state=CmVzKVelhcCWp6Uq6ftQ=%3D&display=page&ip_h=085263ad5a70&hash=1560095643_b996766c01&https=1

  1. Тут я получил код авторизации

https://xxxx.ru/api/oauth2/callback/vk?code= rMt4GzXza4FuqnorlnNO&state=CmVzKVelhcCWp6Uq6ftQ=

  1. далее приходит ошибка

https://xxxx.ru/redirect?error=[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: tokenType cannot be null; nested exception is java.lang.IllegalArgumentException: tokenType cannot be null

Почему tokenType не может быть null не могу понять.

Настройку oauth client я делаю в коде по скольку все конфиги лежал в базе.

Выбор клиента авторизации

public class CustomClientRegistration {
  @Autowired
  private SocialNetworkDataRepository socialNetworkDataRepository;

  public ClientRegistration getRegistration(String registrationId) {

    SocialNetworkDataModel model = socialNetworkDataRepository.findByProvider(AuthProviderEnum.valueOf(registrationId));

    if (model == null) {
      return null;
    }

    AuthProviderEnum client = AuthProviderEnum.valueOf(registrationId);

    ClientRegistration clientRegistration = null;

    if (client == AuthProviderEnum.google) {
      clientRegistration = CustomOAuth2Provider.getGoogle(model);
    }

    if (client == AuthProviderEnum.facebook) {
      clientRegistration = CustomOAuth2Provider.getFacebook(model);
    }

    if (client == AuthProviderEnum.vk) {
      clientRegistration = CustomOAuth2Provider.getVk(model);
    }

    return clientRegistration;
  }
}

Настройка провайдера

public class CustomOAuth2Provider {
  public static ClientRegistration getGoogle(SocialNetworkDataModel model) {
    return CommonOAuth2Provider.GOOGLE.getBuilder(model.getProvider().name())
            .scope(model.getScope().split(","))
            .redirectUriTemplate("{baseUrl}/oauth2/callback/{registrationId}")
            .clientId(model.getAppId()).clientSecret(model.getSecret()).build();
  }

  public static ClientRegistration getVk(SocialNetworkDataModel model) {
    ClientRegistration.Builder builder = getBuilder(model.getProvider().name(), ClientAuthenticationMethod.POST, "{baseUrl}/{action}/oauth2/code/{registrationId}");
    builder.scope(model.getScope().split(","));
    builder.authorizationUri("https://oauth.vk.com/authorize?v=5.95");
    builder.tokenUri("https://oauth.vk.com/access_token");
    builder.userInfoUri("https://api.vk.com/method/users.get");
    builder.clientName("vkontakte");
    builder.redirectUriTemplate("{baseUrl}/oauth2/callback/{registrationId}");
    builder.clientId(model.getAppId());
    builder.clientSecret(model.getSecret());
    builder.registrationId("vk");
    return builder.build();
  }
}

Конфигурация Security

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  private static List<String> clients = Arrays.asList("google", "vk", "facebook");

  @Bean
  protected ClientRegistrationRepository clientRegistrationRepository() {
    List<ClientRegistration> registrations = clients.stream()
        .map(c -> customClientRegistration().getRegistration(c))
        .filter(registration -> registration != null)
        .collect(Collectors.toList());

    return new InMemoryClientRegistrationRepository(registrations);
  }

  @Bean
  public OAuth2AuthorizedClientService authorizedClientService() {

    return new InMemoryOAuth2AuthorizedClientService(
        clientRegistrationRepository());
  }         

  @Override
  protected void configure(final HttpSecurity http) throws Exception {
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and().authorizeRequests().antMatchers("/login").permitAll()
        .anyRequest().authenticated()
        .and().formLogin().permitAll()
        .exceptionHandling().authenticationEntryPoint(new AuthExceptionEntryPoint())
        .and()
        .oauth2Login()
        .clientRegistrationRepository(clientRegistrationRepository())
        .authorizationEndpoint()
        .baseUri("/oauth2/authorize")
        .authorizationRequestRepository(cookieAuthorizationRequestRepository())
        .and()
        .redirectionEndpoint()
        .baseUri("/oauth2/callback/*")
        .and()
        .userInfoEndpoint()
        .userService(customOAuth2UserService)
        .and()
        .successHandler(oAuth2AuthenticationSuccessHandler)
        .failureHandler(oAuth2AuthenticationFailureHandler);

    // Add our custom Token based authentication filter
    http.addFilterBefore(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
  }

  ////*************....
}
10
  • У вас удалось решить проблему? Я сегодня всю ночь просидел и вчерне задачу решил, хотя у меня и очень некрасиво получилось, т.к. пришлось совсем глубоко закопаться в недра спринга чтобы вручную прикреплять токены к запросам и прокидывать email юзера через цепочку запросов. И всё потому, что у ВК сделано странно: мыло возвращается вместе с access_token, запрос на который требует client_id и client_secret в качестве параметров, вместо Basic авторизации, а запрос юзера имеет нестандартный формат и также не принимает токен в заголовке.
    – ЮрийСПб
    4 авг 2019 в 12:11
  • Мне пришлось подсунуть свой accessTokenResponseClient в WebSecurityConfigurerAdapter 5 авг 2019 в 14:35
  • Ага, я примерно так же сделал и как-то оно заработало, хотя нервов съело очень много)
    – ЮрийСПб
    5 авг 2019 в 14:40
  • помогла статься baeldung.com/spring-security-custom-oauth-requests. Реализовал свой CustomTokenResponseConverter от implements Converter<Map<String, String>, OAuth2AccessTokenResponse> где руками проставляю OAuth2AccessToken.TokenType accessTokenType = OAuth2AccessToken.TokenType.BEARER; Как оказалось vk не возвращает тип токена и спрингу сносит крышу. 5 авг 2019 в 14:57
  • Ага, я точно также и сделал и потом эту же статью нашёл) Правда, пришлось ещё с настройками клиента помучиться - ВК хочет form для clientAuthenticationMethod и userInfoAuthenticationMethod.
    – ЮрийСПб
    5 авг 2019 в 15:00

1 ответ 1

5

Потратив почти весь день закопавшись в глубь sprign разбираясь что же не так, я нашел в чем была проблема, надеюсь эта информация кому то сэкономит кучу времени и нервных клеток.

Оказывается Vk в ответе получения токена не возвращается тип токена token_type Bearer, от сюда и срабатывает исключение "tokenType cannot be null". Но это часть проблемы, также Vk в месте с токеном возвращает email пользователя, плюс на запрос информации о пользователе по токену, ответ зачем то заворачивается в дополнительное поле "response" из за этого в OAuth2UserService при попытке получить Map срабатывает исключение. Запрос и разбор ответа пришлось делать вручную.

Для решения этой проблемы мне очень помогли статьи мною глубоко уважаемого Вaeldung.

а также серия статей - авторизация пользователей через социальные сети - https://www.callicoder.com/spring-boot-security-oauth2-social-login-part-1/

1.Oбработчик ответа получения токена.

public class CustomTokenResponseConverter implements Converter<Map<String, String>, OAuth2AccessTokenResponse> {

  @Override
  public OAuth2AccessTokenResponse convert(Map<String, String> tokenResponseParameters) {
    String accessToken = tokenResponseParameters.get(OAuth2ParameterNames.ACCESS_TOKEN);
    long expiresIn = Long.valueOf(tokenResponseParameters.get(OAuth2ParameterNames.EXPIRES_IN));


    OAuth2AccessToken.TokenType accessTokenType = OAuth2AccessToken.TokenType.BEARER;

    Map<String, Object> additionalParameters = new HashMap<>();

    tokenResponseParameters.forEach((s, s2) -> {
      additionalParameters.put(s, s2);
    });

    return OAuth2AccessTokenResponse.withToken(accessToken)
            .tokenType(accessTokenType)
            .expiresIn(expiresIn)
            .additionalParameters(additionalParameters)
            .build();
  }
}

тут и происходит вся магия, вот эта строчка - OAuth2AccessToken.TokenType accessTokenType = OAuth2AccessToken.TokenType.BEARER;

2.Настраиваем клиента получения информации о пользователе по токену. ClientRegistration

  public static ClientRegistration getVk() {
    ClientRegistration.Builder builder = getBuilder("vk", ClientAuthenticationMethod.POST, "{baseUrl}/{action}/oauth2/code/{registrationId}");
    builder.scope("xxxxx");
    builder.authorizationUri("https://oauth.vk.com/authorize?v=5.95");
    builder.tokenUri("https://oauth.vk.com/access_token");
    builder.userInfoUri("https://api.vk.com/method/users.get?{user_id}&v=5.95&fields=photo_id,verified,sex,bdate,city,country,photo_max,home_town,has_photo&display=popup&lang=ru&access_token=xxxxx");
    builder.clientName("vkontakte");
    builder.redirectUriTemplate("{baseUrl}/oauth2/callback/{registrationId}");
    builder.clientId("xxxxx");
    builder.clientSecret("xxxx");
    builder.userNameAttributeName("user_id");
    builder.registrationId("vk");
    return builder.build();
  }

3.Настраиваем CustomOAuth2UserService от DefaultOAuth2UserService где запрашивается информация о пользователе.

@Service
public class CustomOAuth2UserService extends DefaultOAuth2UserService {

  @Override
  public OAuth2User loadUser(OAuth2UserRequest oAuth2UserRequest) throws OAuth2AuthenticationException {

    OAuth2User oAuth2User;
    if (oAuth2UserRequest.getClientRegistration().getRegistrationId().equals("vk")) {
      oAuth2User = loadVkUser(oAuth2UserRequest);
    } else {
      oAuth2User = super.loadUser(oAuth2UserRequest);
    }

    try {
      return processOAuth2User(oAuth2UserRequest, oAuth2User);
    } catch (AuthenticationException ex) {
      throw new AuthException(ex.getMessage());
    } catch (Exception ex) {
      // Throwing an instance of AuthenticationException will trigger the OAuth2AuthenticationFailureHandler
      throw new InternalAuthenticationServiceException(ex.getMessage(), ex.getCause());
    }
  }

  private OAuth2User processOAuth2User(OAuth2UserRequest oAuth2UserRequest, OAuth2User oAuth2User) {
    OAuth2UserInfo oAuth2UserInfo = OAuth2UserInfoFactory.getOAuth2UserInfo(oAuth2UserRequest.getClientRegistration().getRegistrationId(), oAuth2User.getAttributes());

    .....
    return CustomUserPrincipal.create(socialUser, oAuth2User.getAttributes());
  }


  private OAuth2User loadVkUser(OAuth2UserRequest oAuth2UserRequest) {
    RestTemplate template = new RestTemplate();

    MultiValueMap<String, String> headers = new LinkedMultiValueMap();
    headers.add("Content-Type", "application/json");
    headers.add("Authorization", oAuth2UserRequest.getAccessToken().getTokenType().getValue() + " " + oAuth2UserRequest.getAccessToken().getTokenValue());
    HttpEntity<?> httpRequest = new HttpEntity(headers);
    String uri = oAuth2UserRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri();
    String userNameAttributeName = oAuth2UserRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName();
    uri = uri.replace("{user_id}", userNameAttributeName + "=" + oAuth2UserRequest.getAdditionalParameters().get(userNameAttributeName));

    try {
      ResponseEntity<Object> entity = template.exchange(uri, HttpMethod.GET, httpRequest, Object.class);
      Map<String, Object> response = (Map) entity.getBody();
      ArrayList valueList = (ArrayList) response.get("response");
      Map<String, Object> userAttributes = (Map<String, Object>) valueList.get(0);
      userAttributes.put(userNameAttributeName, oAuth2UserRequest.getAdditionalParameters().get(userNameAttributeName));      
      ......

      Set<GrantedAuthority> authorities = Collections.singleton(new OAuth2UserAuthority(userAttributes));
      return new DefaultOAuth2User(authorities, userAttributes, userNameAttributeName);

    } catch (HttpClientErrorException ex) {
      ex.printStackTrace();
      throw new BaseRuntimeException(ex.getMessage(), HttpStatus.UNAUTHORIZED);
    }
  }
}

4.Все классы инициализируем в WebSecurityConfigurerAdapter.

public class SecurityConfig extends WebSecurityConfigurerAdapter {

  private static List<String> clients = Arrays.asList("google", "vk", "facebook", "ok", "yandex");

  @Autowired
  private CustomUserDetailsService customUserDetailsService;

  @Autowired
  private CustomOAuth2UserService customOAuth2UserService;

  @Autowired
  private OAuth2AuthenticationSuccessHandler oAuth2AuthenticationSuccessHandler;

  @Autowired
  private OAuth2AuthenticationFailureHandler oAuth2AuthenticationFailureHandler;

  ....


  @Bean
  protected CustomClientRegistration customClientRegistration() {
    return new CustomClientRegistration();
  }

  @Bean
  protected ClientRegistrationRepository clientRegistrationRepository() {
    List<ClientRegistration> registrations = clients.stream()
        .map(c -> customClientRegistration().getRegistration(c))
        .filter(registration -> registration != null)
        .collect(Collectors.toList());

    return new InMemoryClientRegistrationRepository(registrations);
  }  

  @Override
  protected void configure(final HttpSecurity http) throws Exception {
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .anyRequest().authenticated()
        .and().formLogin().permitAll()
        .and().csrf().disable()
        .formLogin().disable()
        .httpBasic().disable()
        .exceptionHandling().authenticationEntryPoint(new AuthExceptionEntryPoint())
        .and()
        .oauth2Login()
        .clientRegistrationRepository(clientRegistrationRepository())
        .authorizationEndpoint().authorizationRequestResolver(new CustomAuthorizationRequestResolver(clientRegistrationRepository(), "/oauth2/authorize"))
        .authorizationRequestRepository(cookieAuthorizationRequestRepository())
        .and()
        .redirectionEndpoint()
        .baseUri("/oauth2/callback/*")
        .and()
        .userInfoEndpoint()
        .userService(customOAuth2UserService)
        .and()
        .successHandler(oAuth2AuthenticationSuccessHandler)
        .failureHandler(oAuth2AuthenticationFailureHandler);

    // Add our custom Token based authentication filter
    http.addFilterBefore(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    http.oauth2Login().tokenEndpoint().accessTokenResponseClient(accessTokenResponseClient());
  }

  @Bean
  public OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient(){
    DefaultAuthorizationCodeTokenResponseClient accessTokenResponseClient =
            new DefaultAuthorizationCodeTokenResponseClient();
    accessTokenResponseClient.setRequestEntityConverter(new CustomRequestEntityConverter());

    OAuth2AccessTokenResponseHttpMessageConverter tokenResponseHttpMessageConverter =
            new OAuth2AccessTokenResponseHttpMessageConverter();
    tokenResponseHttpMessageConverter.setTokenResponseConverter(new CustomTokenResponseConverter());

    RestTemplate restTemplate = new RestTemplate(Arrays.asList(
            new FormHttpMessageConverter(), tokenResponseHttpMessageConverter));
    restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());

    accessTokenResponseClient.setRestOperations(restTemplate);
    return accessTokenResponseClient;
  }
 }
3
  • Хорошее решение, единственное, что можно предложить - вместо регистрации ClientRegistration и Provider через код явно, можно просто указать соответствующие проперти в yml или properties и автоконфигурация спринг сама добавит новый провайдер и клиента. 1 дек 2019 в 22:56
  • Речь идёт о проперти spring.security.oauth2.client.provider.vk.props и spring.security.oauth2.client.registration.vk.props 1 дек 2019 в 22:57
  • 1
    Согласен, но одно из требований было, чтобы clientId, clientSecret и т.д., тащить из БД при запуске сервиса 3 дек 2019 в 1:03

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.