Downloading from S3 Without Turning Object Keys into an Access Policy

Editorial illustration.

Originally published 16 June 2023; rewritten and reviewed on 15 October 2026.

Almost every quick-start tutorial for Amazon S3 or Cloudflare R2 shows a download endpoint that accepts a key parameter in the URL and passes it straight to GetObjectAsync. It works on localhost in five minutes, and it is a security bug the moment it hits production. An opaque UUID or folder prefix in an object key is not an access control boundary—anyone who guesses or intercepts another tenant’s key can pull their file.

Authorise the document, then find its object

Keep object keys internal. Have the client request an application-level document ID, check whether the signed-in user owns or has permission to read that record, and only then look up the bucket name and object key from your database.

Once the record is authorised, a clean C# retrieval using IAmazonS3 looks like this:

public async Task<IActionResult> Download(int documentId, CancellationToken cancellationToken)
{
    var doc = await _documentRepo.GetAuthorisedAsync(User, documentId, cancellationToken);
    if (doc is null)
    {
        return NotFound();
    }

    try
    {
        var response = await _s3.GetObjectAsync(new GetObjectRequest
        {
            BucketName = doc.BucketName,
            Key = doc.ObjectKey
        }, cancellationToken);

        Response.RegisterForDispose(response);

        var contentType = string.IsNullOrWhiteSpace(doc.ContentType)
            ? "application/octet-stream"
            : doc.ContentType;

        return File(response.ResponseStream, contentType, doc.DownloadFileName);
    }
    catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
    {
        _logger.LogWarning("S3 object missing for document {DocumentId} ({Key})", documentId, doc.ObjectKey);
        return NotFound();
    }
}

Notice Response.RegisterForDispose(response). A common pitfall when returning File(response.ResponseStream, ...) in ASP.NET Core is wrapping GetObjectAsync in a using var response = ... block. Because File(...) streams the response body after the controller action returns, disposing response inside the action closes the underlying network stream before the browser receives a single byte. Registering it for disposal with the HTTP response keeps the stream alive until the transfer finishes.

Proxying through your app vs presigned URLs

Streaming bytes through your web server gives you full control: you can enforce custom audit logs, attach Content-Disposition: attachment headers, and keep the storage endpoint completely invisible to the client. The downside is bandwidth and memory—if your app runs on a modest VM behind a metered connection, every 50 MB PDF download passes through your application process twice (once from S3, once to the user).

The alternative is generating a short-lived presigned URL with _s3.GetPreSignedURL:

var url = _s3.GetPreSignedURL(new GetPreSignedUrlRequest
{
    BucketName = doc.BucketName,
    Key = doc.ObjectKey,
    Expires = DateTime.UtcNow.AddMinutes(5),
    ResponseHeaderOverrides = new ResponseHeaderOverrides
    {
        ContentDisposition = $"attachment; filename=\"{SanitiseFileName(doc.DownloadFileName)}\""
    }
});

With a presigned URL, the browser downloads directly from S3 or R2, taking load off your server. The trade-off is that anyone holding that URL can read the object until it expires, so keep the expiry short (a few minutes, not hours), avoid logging full presigned URLs in application logs or analytics, and use ResponseHeaderOverrides so the browser downloads the file rather than rendering an uploaded .html or .svg inline.

Distinguish missing objects from broken credentials

In production, AmazonS3Exception can mean very different things. A 404 NotFound (NoSuchKey) means your database points to an object that was deleted or never finished uploading. A 403 Forbidden (AccessDenied) usually means an IAM policy, bucket policy, or R2 API token lost s3:GetObject permission—which is an infrastructure incident, not a missing user file.

Log the S3 ErrorCode, HTTP status code, and internal document ID on the server so you can tell the two apart immediately, while returning a generic 404 or 500 to the caller without leaking bucket names or internal keys.