Presigned URLs and S4 extension parameters
A presigned URL embeds the authorization for a single operation in the link. Anyone who has the link can upload or download the specified object during its validity period without an AccessKey. It suits direct uploads and downloads from browsers and apps without relaying through your server.
How it works
An AccessKey is used to compute a signature over "method + bucket + object key + query parameters + validity period", and the signature is placed in the URL together with the parameters. When S4 receives the request, it recomputes the signature and compares.
- Generation happens locally and makes no network requests.
- The link carries the same permissions as the sub-user that generated it. If the sub-user has no permission, the link can still be generated, but accessing it returns 403.
- After you delete the AccessKey or revoke the permissions, links generated with it stop working.
- Parameters cannot be modified. Every query parameter in the URL is part of the signature, and adding, removing, or changing any one returns
SignatureDoesNotMatch.
Validity period
Specified by X-Amz-Expires in seconds, up to 604800 seconds (7 days). A larger value returns 400 AuthorizationQueryParametersError; an expired link returns 403 AccessDenied with the message Request has expired.
For public access over a longer period, use public read or a CDN.
Supported operations
| Method | Operation | Notes |
|---|---|---|
| GET | Download an object | Supports Range, so multithreaded downloads and resumable downloads work |
| HEAD | Retrieve metadata | A link generated for GET can be used directly for HEAD requests |
| PUT | Upload an object, upload a part | For multipart uploads, uploadId and partNumber are also part of the signature |
| POST | Create or complete a multipart upload | |
| DELETE | Delete an object, abort a multipart upload | Issue these with care |
A link cannot be used with a different method. A link generated for GET cannot be used for PUT.
Presigned links are not restricted by the bucket's access control lists or original file protection; they are equivalent to access by a holder of the permissions.
Generate a link
The functions below also support attaching S4 extension parameters. The example uses x-bitiful-max-requests to generate a link that can be used only once and is valid for 10 minutes.
import boto3
from botocore.config import Config
s3 = boto3.client(
"s3",
endpoint_url="https://s3.bitiful.net",
region_name="cn-east-1",
aws_access_key_id="<AccessKey>",
aws_secret_access_key="<SecretKey>",
config=Config(signature_version="s3v4", s3={"addressing_style": "virtual"}),
)
def presign(operation, method, params, expires, extra=None):
"""operation looks like GetObject, and method looks like get_object."""
event = f"before-sign.s3.{operation}"
def add_query(request, **kwargs):
request.params.update(extra or {})
s3.meta.events.register(event, add_query, unique_id="extra-query")
try:
return s3.generate_presigned_url(method, Params=params, ExpiresIn=expires)
finally:
s3.meta.events.unregister(event, unique_id="extra-query")
download_url = presign(
"GetObject", "get_object",
{"Bucket": "my-bucket", "Key": "docs/report.pdf"},
600, {"x-bitiful-max-requests": "1"},
)
upload_url = presign(
"PutObject", "put_object",
{"Bucket": "my-bucket", "Key": "uploads/a.png", "ContentType": "image/png"},
600, {"x-bitiful-max-requests": "1"},
)import { S3Client, GetObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
const s3 = new S3Client({
endpoint: "https://s3.bitiful.net",
region: "cn-east-1",
credentials: { accessKeyId: "<AccessKey>", secretAccessKey: "<SecretKey>" },
// The content is unknown for presigned uploads, so do not attach the default checksum
requestChecksumCalculation: "WHEN_REQUIRED",
});
function presign(command, expiresIn, extraQuery = {}) {
command.middlewareStack.add(
(next) => async (args) => {
Object.assign(args.request.query, extraQuery);
return next(args);
},
{ step: "build", name: "extraQuery" },
);
return getSignedUrl(s3, command, { expiresIn });
}
const downloadUrl = await presign(
new GetObjectCommand({ Bucket: "my-bucket", Key: "docs/report.pdf" }),
600, { "x-bitiful-max-requests": "1" },
);
const uploadUrl = await presign(
new PutObjectCommand({ Bucket: "my-bucket", Key: "uploads/a.png" }),
600, { "x-bitiful-max-requests": "1" },
);For other languages, see Node.js、Go、Python、Java、PHP、.NET、Rust、Ruby、Android、iOS / Swift. For direct browser uploads, see Browser JavaScript.
Use an upload link
curl -X PUT -T ./a.png -H "Content-Type: image/png" "<upload-link>"- If
ContentTypewas specified when signing and appears inX-Amz-SignedHeaders, the upload must send exactly the sameContent-Type. - Any
x-amz-*headers sent with the upload (for examplex-amz-meta-*) must be included as parameters when the link is generated, or the request returns 403. - To upload from a browser, first configure CORS on the bucket.
Override response headers
When generating a download link, you can add these standard parameters to override response headers. They work for GET and HEAD.
| Parameter | Response header overridden |
|---|---|
response-content-type | Content-Type |
response-content-disposition | Content-Disposition |
response-cache-control | Cache-Control |
response-content-encoding | Content-Encoding |
response-content-language | Content-Language |
response-expires | Expires |
For example, to specify the download file name, the boto3 parameter is ResponseContentDisposition='attachment; filename="report.pdf"'。
When accessing through *.s3.bitiful.net, a Content-Disposition of inline is changed to attachment. To preview in the browser, use a CDN domain.
S4 extension parameters
Like ordinary query parameters, extension parameters must be added before signing; you cannot append them to an already signed URL.
| Parameter | Value | Applies to | Notes |
|---|---|---|---|
x-bitiful-max-requests | Integer greater than 0 | GET, PUT | Maximum number of successful requests |
x-amz-limit-rate | Integer in bytes per second, at least 1024 | GET | Per-connection download rate limit |
no-wait | Integer from 0 to 10, in seconds | GET | Simul-Transfer: how long to wait while the object is still being uploaded |
| CoreIX parameters | See CoreIX | GET | Real-time image and video processing |
Limit the number of requests
x-bitiful-max-requests=N limits a link to at most N uses; the (N+1)th request returns 403 ReachTheMaxRequests.
Counting rules:
- Only effective for V4 presigned links, and counted separately for each link (signature). A regenerated link starts counting again.
- For downloads, if the connection drops after less than one third of the expected content was transferred, that request is not counted.
- Failed uploads are not counted.
- HEAD requests are not counted.
- Each Range request counts once. Multithreaded downloaders and video players send multiple Range requests, so set the limit high enough.
An empty value, 0, a negative number, or a non-integer means no limit.
When issuing upload links, set a short validity period together with x-bitiful-max-requests=1 to prevent replay. For more usage, see Request limits for presigned URLs.
Per-connection rate limit
x-amz-limit-rate=1048576 limits the download speed of a single connection to 1 MiB/s. x-bitiful-limit-rate is an alias for it; if both appear, x-bitiful-limit-rate takes precedence.
- The limit applies to a single connection. When a client opens multiple connections, the total speed adds up; you can combine it with the request limit.
- It is for lowering speed. Direct S4 connections already have a per-connection rate limit, and the parameter cannot raise the speed above the bucket's ceiling; see Product updates. For higher speeds, use a CDN.
Simul-Transfer
no-wait=N is used for Simul-Transfer: downloading starts while the object is still being uploaded.
- N is the maximum number of seconds to wait while the object does not exist yet. If the upload starts during the wait, the download starts right away; if the object still does not exist after the timeout, the request returns 404.
- If the parameter is present but its value is invalid or outside 0 to 10, it is treated as 5 seconds.
- Objects uploaded with multipart upload are not supported; use PutObject to upload.
Media processing
CoreIX processing parameters (for example w, fmt, and q) must also be added before signing:
https://my-bucket.s3.bitiful.net/photo.jpg?w=800&fmt=webp&X-Amz-Algorithm=...&X-Amz-Signature=...- Image processing on a private bucket must be signed this way; appending
?w=800after signing returnsSignatureDoesNotMatch. - The original file to process cannot exceed 200 MiB (video and frame extraction excepted), or the request returns 403
TooLargeForCoreIX.
FAQ
Returns SignatureDoesNotMatch
The most common causes: the URL was modified after signing; the method does not match; Content-Type does not match; an intermediate proxy rewrote the Host or path. For the complete checklist, see Error codes and troubleshooting.
The link expired before its validity period ended
Check that the clock of the machine that generated the link is accurate. The validity period counts from X-Amz-Date, so a slow clock makes the link expire early.
Can I replace the domain of a presigned link with a CDN domain?
No. Access presigned links through the bucket domain. For temporary access authorization on a CDN, use the CDN's advanced hotlink protection.
Can one link limit both the request count and the speed?
Yes. Extension parameters can be used together, and also with response-* and CoreIX parameters.
Related projects
- s3-presigned-api-server: an open-source stateless signing service that wraps the parameters above.
- Upload files securely from the client