|
| 1 | +import java.util.Arrays; |
| 2 | + |
| 3 | +import com.google.api.client.http.GenericUrl; |
| 4 | +import com.google.api.client.http.HttpRequest; |
| 5 | +import com.google.api.client.http.HttpRequestFactory; |
| 6 | +import com.google.api.client.http.HttpResponse; |
| 7 | +import com.google.api.client.http.javanet.NetHttpTransport; |
| 8 | +import com.google.api.client.json.JsonObjectParser; |
| 9 | +import com.google.api.client.json.gson.GsonFactory; |
| 10 | +import com.google.auth.http.HttpCredentialsAdapter; |
| 11 | +import com.google.auth.oauth2.GoogleCredentials; |
| 12 | + |
| 13 | +public class ServiceAccount { |
| 14 | +public static void main(String[] args) throws Exception { |
| 15 | + // String bucketName = "byoid-test-gcs-bucket"; |
| 16 | + String bucketName = "oidc-test"; |
| 17 | + String url = "https://storage.googleapis.com/storage/v1/b/" + bucketName; |
| 18 | + |
| 19 | + GoogleCredentials googleCredentials = GoogleCredentials.getApplicationDefault(); |
| 20 | + // Add scopes to the credentials. This will force the use of the OAuth2 access token flow |
| 21 | + // instead of the self-signed JWT flow. |
| 22 | + String[] scopes = new String[] { "https://www.googleapis.com/auth/cloud-platform" }; |
| 23 | + |
| 24 | + googleCredentials = googleCredentials.createScoped(Arrays.asList(scopes)); |
| 25 | + System.out.println(googleCredentials.getClass().getSimpleName()); |
| 26 | + |
| 27 | + HttpCredentialsAdapter credentialsAdapter = new HttpCredentialsAdapter(googleCredentials); |
| 28 | + HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory(credentialsAdapter); |
| 29 | + HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(url)); |
| 30 | + |
| 31 | + JsonObjectParser parser = new JsonObjectParser(GsonFactory.getDefaultInstance()); |
| 32 | + request.setParser(parser); |
| 33 | + |
| 34 | + HttpResponse response = request.execute(); |
| 35 | + System.out.println(String.format("Success: %s", response.parseAsString())); |
| 36 | +} |
| 37 | + |
| 38 | +} |
0 commit comments