I am working in the Google Drive API integration to my project during this, I wanted to use Google drive service as a service to my application because I don't want each user to log in via Google account to retrieve and upload any file in the cloud storage.
So I started using different approaches provided for Google API (Web application, Stand alone application and As a service account). All these accounts require authentication Via OATH 2.0.
I did some Goggling for the solution and finally found a solution to use service account, by hoping this may help other writing this.
First login to API Console and create a service account. Once service account is created download private key file and use it for service account authentication.
Constants
private static final String KEY_TYPE = "PKCS12";
private static final String KEY_ALIAS = "privatekey";
private static final String KEY_PASSWORD = "notasecret";
private static final String KEY = "YOUR_PRIVATE_KEY.p12";
private static final String SERVICE_ACCOUNT_EMAIL = YOUR_SERVICE_ACCOUNT;
private static final List<String> SCOPES = Arrays.asList(YOUR_API_SCOPES);
public static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
public static final JsonFactory JSON_FACTORY = new JacksonFactory();
Key Validation
Preconditions.checkArgument(!SERVICE_ACCOUNT_EMAIL.startsWith("[["), "Please enter your service account e-mail from the Google APIs Console to the " +
"SERVICE_ACCOUNT_EMAIL constant in %s", GAuthentication.class.getName());
InputSupplier < InputStream > inputSupplier = new InputSupplier < InputStream > () {
public InputStream getInput() throws IOException {
return GAuthentication.class.getResourceAsStream(KEY);
};
};
String p12Content = CharStreams.readFirstLine(CharStreams.newReaderSupplier(inputSupplier, Charset.defaultCharset()));
Preconditions.checkArgument(!p12Content.startsWith("Please"), p12Content)
Create Google Credential
KeyStore keyStore = KeyStore.getInstance(KEY_TYPE);
InputStream keyStream = GAuthentication.class.getResourceAsStream(KEY);
PrivateKey privateKey = PrivateKeys.loadFromKeyStore(keyStore, keyStream, KEY_PASSWORD, KEY_ALIAS, KEY_PASSWORD);
Builder builder = new GoogleCredential.Builder();
builder.setTransport(HTTP_TRANSPORT);
builder.setJsonFactory(JSON_FACTORY);
builder.setServiceAccountId(SERVICE_ACCOUNT_EMAIL);
builder.setServiceAccountScopes(SCOPES);
builder.setServiceAccountPrivateKey(privateKey);
credential = builder.build();