Получить информацию о канале YouTube с помощью googleIdToken - PullRequest
0 голосов
/ 28 октября 2019

В моих веб-сервисах я должен убедиться, что у пользователя есть канал на YouTube.

В моих веб-сервисах у меня есть эта информация:

  • GoogleIdToken: с помощью согласия Google OAuth2screen в моем клиентском приложении.

Я хочу получить каналы Youtube аккаунта Google без OAuth2, потому что я сделаю это в бэкэнде, поэтому я не могу отобразить экран согласия GoogleOAuth2 для пользователя.

Я проверил документацию , но все методы канала используют OAuth2.

Если бы я использовал list (my channel) метод с idToken , это было бы идеально.

Вот мой код авторизации:

@Component
@RequiredArgsConstructor
public class YoutubeDataApiVerifier {

    private static final String CLIENT_SECRETS= "client_secret.json";
    private static final Collection<String> SCOPES =
            Arrays.asList("https://www.googleapis.com/auth/youtube.readonly");

    private static final String APPLICATION_NAME = "Fame Things";
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

    /**
     * Create an authorized Credential object.
     *
     * @return an authorized Credential object.
     * @throws IOException
     */
    public Credential authorize(final NetHttpTransport httpTransport, GoogleIdToken idToken, String token) throws Exception {
        File file = ResourceUtils.getFile("classpath:" + CLIENT_SECRETS);
        InputStream in = new FileInputStream(file);
        GoogleClientSecrets clientSecrets =
                GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow =
                new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets, SCOPES)
                        .build();
        /**
         * ***************************************************************
         * This line prints a Google OAuth2 Consent Screen to the console.
         * But  the user already authorized at client app and I send googleId token to the backend.
         * It should give me the credentials without consent screen but I am missing something.
         */
        Credential credential =
                new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize(token);
        return credential;
    }

    /**
     * Build and return an authorized API client service.
     *
     * @return an authorized API client service
     * @throws GeneralSecurityException, IOException
     */
    public YouTube getService(GoogleIdToken idToken, String token) throws Exception {
        final NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        Credential credential = authorize(httpTransport, idToken, token);
        return new YouTube.Builder(httpTransport, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME)
                .build();
    }


    public String getMyChannel(GoogleIdToken idToken, String token) throws Exception {
        YouTube youtubeService = getService(idToken, token);
        // Define and execute the API request
        YouTube.Channels.List request = youtubeService.channels()
                .list("snippet,contentDetails,statistics");
        ChannelListResponse response = request.setMine(true).execute();
        return response.toPrettyString();
    }
}

Проблема в этой строке:

Credential credential =
        new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize(token);

У меня есть GoogleIdToken в бэкэнде, могу ли я получить учетные данные с ним?

...