2

I am very new to google API and I am having troubles with it. I red documentation Google photos API for Java, then I created OAuth credentials in google API console and downloaded it (credentials.json file). After that I tried to access google photos. Here is code from documentation:

// Set up the Photos Library Client that interacts with the API
PhotosLibrarySettings settings =
   PhotosLibrarySettings.newBuilder()
  .setCredentialsProvider(
      FixedCredentialsProvider.create(/* Add credentials here. */)) 
  .build();

try (PhotosLibraryClient photosLibraryClient =
    PhotosLibraryClient.initialize(settings)) {

  // Create a new Album  with at title
  Album createdAlbum = photosLibraryClient.createAlbum("My Album");

  // Get some properties from the album, such as its ID and product URL
  String id = album.getId();
  String url = album.getProductUrl();

 } catch (ApiException e) {
    // Error during album creation
 }

But I don't understand how to create Credentials object to pass it to the FixedCredentialsProvider.create() method

Could you please provide me with some explanation/links about it?

Fairy
  • 509
  • 1
  • 9
  • 27
  • You might want to have a look at the samples https://github.com/google/java-photoslibrary/tree/master/sample and check that file https://github.com/google/java-photoslibrary/blob/master/sample/src/main/java/com/google/photos/library/sample/factories/PhotosLibraryClientFactory.java – Daniel Przybylowski Oct 11 '18 at 15:39

3 Answers3

4

You can create a UserCredentials Object and pass it

UserCredentials.newBuilder()
        .setClientId("your client id")
        .setClientSecret("your client secret")
        .setAccessToken("Access Token")
        .build()

Go through this answer https://stackoverflow.com/a/54533855/6153171

Or check out this complete project on github https://github.com/erickogi/AndroidGooglePhotosApi

Eric Kogi
  • 89
  • 1
  • 6
  • 2
    @Kogieric I have a question in below link. I can't authenticate access because I don't have refreshToken when request to google. Do you have any solution for this? Thanks. https://github.com/googleapis/google-oauth-java-client/issues/249 – Hoang Feb 14 '19 at 10:32
  • @Hoang You can get access token by calling https://www.googleapis.com/oauth2/v4/token and providing client_id, client_secret – Eric Kogi Feb 19 '19 at 07:22
2

The FixedCredentialsProvider.create(..) call takes in a com.google.auth.Credentials object. For the Google Photos Library API, this should be a UserCredentials object, that you can create UserCredentials.Builder that is part of the Google OAuth library. There you set the refresh token, client ID, client secret, etc. to initialise the credentials. Getting a refresh token requires your app to complete the GoogleAuthorizationCodeFlow that prompts the user for authorization and approval.

You can check out the sample implementation on GitHub, but this is the relevant code:

  GoogleAuthorizationCodeFlow flow =
        new GoogleAuthorizationCodeFlow.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                JSON_FACTORY,
                clientSecrets,
                selectedScopes)
            .setDataStoreFactory(new FileDataStoreFactory(DATA_STORE_DIR))
            .setAccessType("offline")
            .build();
    LocalServerReceiver receiver =
        new LocalServerReceiver.Builder().setPort(LOCAL_RECEIVER_PORT).build();
    Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
    return UserCredentials.newBuilder()
        .setClientId(clientId)
        .setClientSecret(clientSecret)
        .setRefreshToken(credential.getRefreshToken())
        .build();

There are a few moving parts involved, but the Google Photos Library API client library works with the Google Authentication library to handle OAuth authentication.

  • 2
    Do you know if it's possible to connect to the Google Photos API via the Google Sign-In for Android ? When the the latter is already integrated it seems redundant and error prone to go through this routine https://stackoverflow.com/questions/33998335/how-to-get-access-token-after-user-is-signed-in-from-gmail-in-android to create the UserCredentials – Gauthier Nov 15 '18 at 13:47
  • @Jan-Felix Schmakeit: I have a question about your above code and it was description in below link. I can't authenticate access because I don't have refreshToken when request to google. Do you have any solution for this? Thanks. https://github.com/googleapis/google-oauth-java-client/issues/249 – Hoang Feb 14 '19 at 10:37
  • @Jan-Felix Schmakeit , I have a problem when create UserCredential. With Android app , Oauth 2.0 Clien doesn't have **client secret**, even in json file. Do you have any solution for this? – ninhnau19 Aug 16 '22 at 07:39
0

You need to understand about OAuth 2 first: https://www.digitalocean.com/community/tutorials/an-introduction-to-oauth-2

Then you can look this answer https://stackoverflow.com/a/54533855/6153171

P/s: 1. Grant Type: Authorization Code Google developer console : credential is web client.

GoogleApiClient -> addScope, requestServerCode -> grand permission -> get account -> getServerAuthenCode -> get AccessToken (https://stackoverflow.com/a/54533855/6153171) -> I tested and it works well. You can follow this way

  1. Grant Type: Implicit Google developer console : credential is android or ios app.

GoogleApiClient -> addScope, requestTokenID -> grand permission -> get account -> getTokenID -> get AccessToken. I didn't try successfully to grant authorization for google photo api. But with firebase authentication, we can use this way because firebase support class util for us.

user2481102
  • 86
  • 1
  • 5