Search in sources :

Example 1 with ServiceAccountCredentials

use of com.google.auth.oauth2.ServiceAccountCredentials in project google-cloud-java by GoogleCloudPlatform.

the class StorageImplTest method testSignUrlWithOptions.

@Test
public void testSignUrlWithOptions() throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, UnsupportedEncodingException {
    EasyMock.replay(storageRpcMock);
    ServiceAccountCredentials credentials = new ServiceAccountCredentials(null, ACCOUNT, privateKey, null, null);
    storage = options.toBuilder().setCredentials(credentials).build().getService();
    URL url = storage.signUrl(BLOB_INFO1, 14, TimeUnit.DAYS, Storage.SignUrlOption.httpMethod(HttpMethod.POST), Storage.SignUrlOption.withContentType(), Storage.SignUrlOption.withMd5());
    String stringUrl = url.toString();
    String expectedUrl = new StringBuilder("https://storage.googleapis.com/").append(BUCKET_NAME1).append('/').append(BLOB_NAME1).append("?GoogleAccessId=").append(ACCOUNT).append("&Expires=").append(42L + 1209600).append("&Signature=").toString();
    assertTrue(stringUrl.startsWith(expectedUrl));
    String signature = stringUrl.substring(expectedUrl.length());
    StringBuilder signedMessageBuilder = new StringBuilder();
    signedMessageBuilder.append(HttpMethod.POST).append('\n').append(BLOB_INFO1.getMd5()).append('\n').append(BLOB_INFO1.getContentType()).append('\n').append(42L + 1209600).append("\n/").append(BUCKET_NAME1).append('/').append(BLOB_NAME1);
    Signature signer = Signature.getInstance("SHA256withRSA");
    signer.initVerify(publicKey);
    signer.update(signedMessageBuilder.toString().getBytes(UTF_8));
    assertTrue(signer.verify(BaseEncoding.base64().decode(URLDecoder.decode(signature, UTF_8.name()))));
}
Also used : Signature(java.security.Signature) ServiceAccountCredentials(com.google.auth.oauth2.ServiceAccountCredentials) URL(java.net.URL) Test(org.junit.Test)

Example 2 with ServiceAccountCredentials

use of com.google.auth.oauth2.ServiceAccountCredentials in project google-cloud-java by GoogleCloudPlatform.

the class StorageImplTest method testSignUrl.

@Test
public void testSignUrl() throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, UnsupportedEncodingException {
    EasyMock.replay(storageRpcMock);
    ServiceAccountCredentials credentials = new ServiceAccountCredentials(null, ACCOUNT, privateKey, null, null);
    storage = options.toBuilder().setCredentials(credentials).build().getService();
    URL url = storage.signUrl(BLOB_INFO1, 14, TimeUnit.DAYS);
    String stringUrl = url.toString();
    String expectedUrl = new StringBuilder("https://storage.googleapis.com/").append(BUCKET_NAME1).append('/').append(BLOB_NAME1).append("?GoogleAccessId=").append(ACCOUNT).append("&Expires=").append(42L + 1209600).append("&Signature=").toString();
    assertTrue(stringUrl.startsWith(expectedUrl));
    String signature = stringUrl.substring(expectedUrl.length());
    StringBuilder signedMessageBuilder = new StringBuilder();
    signedMessageBuilder.append(HttpMethod.GET).append("\n\n\n").append(42L + 1209600).append("\n/").append(BUCKET_NAME1).append('/').append(BLOB_NAME1);
    Signature signer = Signature.getInstance("SHA256withRSA");
    signer.initVerify(publicKey);
    signer.update(signedMessageBuilder.toString().getBytes(UTF_8));
    assertTrue(signer.verify(BaseEncoding.base64().decode(URLDecoder.decode(signature, UTF_8.name()))));
}
Also used : Signature(java.security.Signature) ServiceAccountCredentials(com.google.auth.oauth2.ServiceAccountCredentials) URL(java.net.URL) Test(org.junit.Test)

Example 3 with ServiceAccountCredentials

use of com.google.auth.oauth2.ServiceAccountCredentials in project google-cloud-java by GoogleCloudPlatform.

the class StorageImplTest method testSignUrlForBlobWithSpecialChars.

@Test
public void testSignUrlForBlobWithSpecialChars() throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, UnsupportedEncodingException {
    // List of chars under test were taken from
    // https://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters
    char[] specialChars = new char[] { '!', '#', '$', '&', '\'', '(', ')', '*', '+', ',', ':', ';', '=', '?', '@', '[', ']' };
    EasyMock.replay(storageRpcMock);
    ServiceAccountCredentials credentials = new ServiceAccountCredentials(null, ACCOUNT, privateKey, null, null);
    storage = options.toBuilder().setCredentials(credentials).build().getService();
    for (char specialChar : specialChars) {
        String blobName = "/a" + specialChar + "b";
        URL url = storage.signUrl(BlobInfo.newBuilder(BUCKET_NAME1, blobName).build(), 14, TimeUnit.DAYS);
        String escapedBlobName = UrlEscapers.urlFragmentEscaper().escape(blobName).replace("?", "%3F");
        String stringUrl = url.toString();
        String expectedUrl = new StringBuilder("https://storage.googleapis.com/").append(BUCKET_NAME1).append(escapedBlobName).append("?GoogleAccessId=").append(ACCOUNT).append("&Expires=").append(42L + 1209600).append("&Signature=").toString();
        assertTrue(stringUrl.startsWith(expectedUrl));
        String signature = stringUrl.substring(expectedUrl.length());
        StringBuilder signedMessageBuilder = new StringBuilder();
        signedMessageBuilder.append(HttpMethod.GET).append("\n\n\n").append(42L + 1209600).append("\n/").append(BUCKET_NAME1).append(escapedBlobName);
        Signature signer = Signature.getInstance("SHA256withRSA");
        signer.initVerify(publicKey);
        signer.update(signedMessageBuilder.toString().getBytes(UTF_8));
        assertTrue(signer.verify(BaseEncoding.base64().decode(URLDecoder.decode(signature, UTF_8.name()))));
    }
}
Also used : Signature(java.security.Signature) ServiceAccountCredentials(com.google.auth.oauth2.ServiceAccountCredentials) URL(java.net.URL) Test(org.junit.Test)

Example 4 with ServiceAccountCredentials

use of com.google.auth.oauth2.ServiceAccountCredentials in project google-cloud-java by GoogleCloudPlatform.

the class StorageImplTest method testSignUrlForBlobWithSlashes.

@Test
public void testSignUrlForBlobWithSlashes() throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, UnsupportedEncodingException {
    EasyMock.replay(storageRpcMock);
    ServiceAccountCredentials credentials = new ServiceAccountCredentials(null, ACCOUNT, privateKey, null, null);
    storage = options.toBuilder().setCredentials(credentials).build().getService();
    String blobName = "/foo/bar/baz #%20other cool stuff.txt";
    URL url = storage.signUrl(BlobInfo.newBuilder(BUCKET_NAME1, blobName).build(), 14, TimeUnit.DAYS);
    String escapedBlobName = UrlEscapers.urlFragmentEscaper().escape(blobName);
    String stringUrl = url.toString();
    String expectedUrl = new StringBuilder("https://storage.googleapis.com/").append(BUCKET_NAME1).append(escapedBlobName).append("?GoogleAccessId=").append(ACCOUNT).append("&Expires=").append(42L + 1209600).append("&Signature=").toString();
    assertTrue(stringUrl.startsWith(expectedUrl));
    String signature = stringUrl.substring(expectedUrl.length());
    StringBuilder signedMessageBuilder = new StringBuilder();
    signedMessageBuilder.append(HttpMethod.GET).append("\n\n\n").append(42L + 1209600).append("\n/").append(BUCKET_NAME1).append(escapedBlobName);
    Signature signer = Signature.getInstance("SHA256withRSA");
    signer.initVerify(publicKey);
    signer.update(signedMessageBuilder.toString().getBytes(UTF_8));
    assertTrue(signer.verify(BaseEncoding.base64().decode(URLDecoder.decode(signature, UTF_8.name()))));
}
Also used : Signature(java.security.Signature) ServiceAccountCredentials(com.google.auth.oauth2.ServiceAccountCredentials) URL(java.net.URL) Test(org.junit.Test)

Example 5 with ServiceAccountCredentials

use of com.google.auth.oauth2.ServiceAccountCredentials in project java-docs-samples by GoogleCloudPlatform.

the class BuildIapRequest method buildIapRequest.

/**
 * Clone request and add an IAP Bearer Authorization header with signed JWT token.
 *
 * @param request Request to add authorization header
 * @param iapClientId OAuth 2.0 client ID for IAP protected resource
 * @return Clone of request with Bearer style authorization header with signed jwt token.
 * @throws Exception exception creating signed JWT
 */
public static HttpRequest buildIapRequest(HttpRequest request, String iapClientId) throws Exception {
    // get service account credentials
    ServiceAccountCredentials credentials = getCredentials();
    // get the base url of the request URL
    String jwt = getSignedJwt(credentials, iapClientId);
    if (jwt == null) {
        throw new Exception("Unable to create a signed jwt token for : " + iapClientId + "with issuer : " + credentials.getClientEmail());
    }
    String idToken = getGoogleIdToken(jwt);
    if (idToken == null) {
        throw new Exception("Unable to retrieve open id token");
    }
    // Create an authorization header with bearer token
    HttpHeaders httpHeaders = request.getHeaders().clone().setAuthorization("Bearer " + idToken);
    // create request with jwt authorization header
    return httpTransport.createRequestFactory().buildRequest(request.getRequestMethod(), request.getUrl(), request.getContent()).setHeaders(httpHeaders);
}
Also used : HttpHeaders(com.google.api.client.http.HttpHeaders) ServiceAccountCredentials(com.google.auth.oauth2.ServiceAccountCredentials)

Aggregations

Test (org.junit.Test)18 MockTokenServerTransportFactory (com.google.auth.oauth2.GoogleCredentialsTest.MockTokenServerTransportFactory)10 ServiceAccountCredentials (com.google.auth.oauth2.ServiceAccountCredentials)10 URL (java.net.URL)5 Signature (java.security.Signature)5 MockLowLevelHttpResponse (com.google.api.client.testing.http.MockLowLevelHttpResponse)3 Metadata (io.grpc.Metadata)3 KeyPair (java.security.KeyPair)3 GenericJson (com.google.api.client.json.GenericJson)2 GoogleCredentials (com.google.auth.oauth2.GoogleCredentials)2 SimpleRequest (io.grpc.testing.integration.Messages.SimpleRequest)2 SimpleResponse (io.grpc.testing.integration.Messages.SimpleResponse)2 IOException (java.io.IOException)2 URI (java.net.URI)2 HttpHeaders (com.google.api.client.http.HttpHeaders)1 FixedClock (com.google.api.client.testing.http.FixedClock)1 HttpTransportFactory (com.google.auth.http.HttpTransportFactory)1 AccessToken (com.google.auth.oauth2.AccessToken)1 FirebaseOptions (com.google.firebase.FirebaseOptions)1 Date (java.util.Date)1