Skip to content

Instantly share code, notes, and snippets.

@pavel-alay
Last active June 28, 2021 04:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pavel-alay/a8c060f88368494ec393c232a6549df6 to your computer and use it in GitHub Desktop.
Save pavel-alay/a8c060f88368494ec393c232a6549df6 to your computer and use it in GitHub Desktop.
Google OAuth Playground
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.gmail.GmailScopes;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;
// See also: https://developers.google.com/oauthplayground/
public class GoogleOAuthPlayground {
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
private static final List<String> SCOPES = Collections.singletonList(GmailScopes.GMAIL_MODIFY);
private static final String CREDENTIALS_FILE_PATH = "google_client_secret.json";
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
try(InputStream in = new FileInputStream(CREDENTIALS_FILE_PATH)) {
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8880).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
}
public static void main(String[] args) throws IOException, GeneralSecurityException {
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
Credential credentials = getCredentials(HTTP_TRANSPORT);
System.out.printf("AccessToken:\n%s\n\nRefreshToken:\n%s\n%n",
credentials.getAccessToken(), credentials.getRefreshToken());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment