André Luiz
André Luiz

Reputation: 7302

Google Cloud Storage getting download link

I'm working in an Asp.Net Core 2 web api for files hosted at Google Cloud Storage. The files hosted there are not public, so I can't use the MediaLink property of the object. I tried to make a download endpoint using MemoryStream but when there are many users downloading large files at once I run into memory issues.

My question is: is there a way to create something link a one-time download link for a file or something similar?

I'm also trying to implement what's described in this link but I'd need to give the bearer token to the user. I can't do that.

Any tips?

Upvotes: 6

Views: 7803

Answers (2)

André Luiz
André Luiz

Reputation: 7302

I managed to Create it using C#. I'm posting here because this will be useful to someone else:

1 - Create your private key 2 - Create and UrlSigner:

private readonly UrlSigner _urlSigner;

2 - In your class constructor:

    using (var stream = File.OpenRead(_googleSettings.StorageAuthJson))
    {
        _urlSigner = UrlSigner.FromServiceAccountData(stream);
    }

_googleSettings.StorageAuthJson has the physical path of the json file you downloaded when creating your key.

3 - Method to get the URL:

public string GetSignedUrl(string bucketName, string objectName, TimeSpan duration) {
    var url = _urlSigner.Sign(bucketName, objectName, duration, null);
    return url;
}

Upvotes: 2

Brandon Yarbrough
Brandon Yarbrough

Reputation: 38389

Yes. Google Cloud Storage offers a feature called "signed URLs" that is what you described: a URL that is only good for a short while to download a single file. The idea is that you craft a download URL, then use the private key of a service account to "sign" the URL. Anyone holding that final URL can use it to act as that service account for the purpose of downloading that one object.

Take a look: https://cloud.google.com/storage/docs/access-control/#Signed-URLs

Writing code to generate the signed URL is a bit tricky, but the client libraries provide helper methods in several languages to do it for you. You can also generate one with the gsutil command: gsutil signurl -d 10m privatekey.p12 gs://bucket/foo

There is a code sample for generating he signed URLs programatically on their GitHub project: Signed URLs

Upvotes: 7

Related Questions