How to Generate Expires Value for Amazon S3 or Google Cloud Storage Using Java

Google Cloud Storage and Amazon S3 supports signed URLs for protected objects. Signed URLs can be used to enable temporary public access to protected content. Anyone with the signed URL can access the protected resource. However the validity of the signed URL is specified by a query parameter named Expires. This parameter specifies the validity of the signed URL in terms of seconds elapsed since 1st January 1970 (also know as epoch).

Following is a sample signed URL to a protected Google cloud storage object (signature is truncated for brevity),

https://storage.googleapis.com/samplebucket/samplefile.jpg? GoogleAccessId=serviceuser@demoaccount-12345.iam.gserviceaccount.com& Expires=1487561198&Signature=nVmsboiEMOBZONx…

In the above URL, the Expires value specifies the validity of the URL as the number of seconds since 1st January 1970 (UTC).

Generating Expires Value in Java

The following simple method in Java can be used to generate Expires query parameter in an Amazon S3 or Google cloud storage signed URL. It will calculate an expiry time since the execution of the method itself. The parameter to the method is the number of seconds of validity of the signed URL since the execution of the method.

    // Return an Expires value calculated as number of seconds of validity from now!
    private long getExpiresForSecondsSinceNow(long seconds) {
        long now = System.currentTimeMillis();
        long expiryTime = (now + seconds*1000L)/1000; // convert millis to seconds
        return expiryTime;
    }

Note that the Expires field in the signed URL query parameter must be the same one specified in the original signed text used for generation of signed URL. If you are using signed URLs for delivering protected media content such as video or images, it is important to keep a short expiry time such as 60 seconds.

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution! Please email us.

Leave a Reply