Attachments in S3 from Spring Boot: Pre-signed Uploads, a 302 to a Pre-signed Download, and Links That Expire
A support ticket gets a screenshot, and the API never touches the bytes. It hands out a signed PUT valid for 600 seconds, records the key when the browser confirms, and answers downloads with a 302 to a signed GET valid for 300. The plain object URL gets 403, and a 5-second link works once, then says Request has expired.
What you will learn
- Keep the bucket private and let files skip the API entirely
- Sign a PUT URL with S3Presigner so the browser uploads straight to S3
- Answer a download with 302 to a short-lived signed GET
- Read the parts of a signed URL and see an expired link refused
Before you start
- The AWS SDK for Java v2 in Spring Boot: Clients as Beans, the Default Credentials Chain and No Keys in Code
- Private S3 Uploads from FastAPI: A Locked Bucket, a Key per User, and Presigned Links That Expire
Relay's attachments used to sit on the API's own disk, and every byte went through the API twice: once up, once down. That doesn't survive two copies of the API, and it wastes the API's threads on file transfer. The fix is a private S3 bucket and signed links. The API decides who may upload or download. S3 moves the bytes.
The runs below used MinIO, an S3-compatible store, on localhost:9000. On AWS, only the host in the URLs changes, to the bucket's own address.
Three arrows
The signer
@Bean
S3Presigner s3Presigner(AttachmentProperties props) {
S3Presigner.Builder b = S3Presigner.builder().region(Region.of(props.region()));
if (props.endpoint() != null && !props.endpoint().isBlank()) { // a local S3-compatible store only
b.endpointOverride(URI.create(props.endpoint()))
.serviceConfiguration(S3Configuration.builder().pathStyleAccessEnabled(true).build());
}
return b.build();
}
S3Presigner comes from the AWS SDK's s3 module. It doesn't call S3 at all: it signs a URL locally with the app's credentials, found by the default chain (a profile on a laptop, the task role on ECS). That's why signing is fast. It also means a signed URL can only do what the signer itself is allowed to do.
Step 1: an upload slip
public UploadSlip uploadUrl(long ticketId, String fileName, String contentType) {
String key = "tickets/" + ticketId + "/" + UUID.randomUUID() + "-" + fileName;
PutObjectPresignRequest request = PutObjectPresignRequest.builder()
.signatureDuration(props.uploadTtl())
.putObjectRequest(o -> o.bucket(props.bucket()).key(key).contentType(contentType))
.build();
String url = presigner.presignPutObject(request).url().toString();
return new UploadSlip(key, url, props.uploadTtl().toSeconds());
}
The API picks the key, not the browser: tickets/42/<uuid>-printer-error.png. The UUID means two files with the same name never overwrite each other. POST /api/tickets/42/attachments/upload-url with {"fileName":"printer-error.png","contentType":"image/png"} answered with the key, the URL and "expiresInSeconds":600.
What's in a signed URL
The URL is the object's address plus query parameters:
| Parameter | Meaning |
|---|---|
X-Amz-Algorithm=AWS4-HMAC-SHA256 | how it was signed |
X-Amz-Credential | whose key signed it (an access key id and a scope, never the secret) |
X-Amz-Date, X-Amz-Expires=600 | when it was signed, and for how many seconds it works |
X-Amz-SignedHeaders=content-type;host | headers that must match, so the PUT has to send image/png |
X-Amz-Signature | the signature over all of the above |
Change any part, a longer expiry or another key, and the signature no longer matches.
Step 2 and 3: upload, then confirm
The browser sends the file with a plain PUT to that URL, with Content-Type: image/png. The store answered 200. Then the browser tells the API it's done:
public Attachment confirm(long ticketId, String key, String fileName) {
if (!key.startsWith("tickets/" + ticketId + "/")) {
throw new IllegalArgumentException("key does not belong to ticket " + ticketId);
}
Attachment a = new Attachment(ids.incrementAndGet(), ticketId, key, fileName);
saved.put(a.id(), a);
return a;
}
The check stops a caller from attaching some other ticket's file to this one. The answer was {"id":1,"ticketId":42,"key":"tickets/42/...-printer-error.png","fileName":"printer-error.png"}. (Relay keeps these rows in its attachment table; the demo uses a map.)
Step 4: download with a 302
public String downloadUrl(long attachmentId) {
Attachment a = saved.get(attachmentId);
if (a == null) {
return null;
}
GetObjectPresignRequest request = GetObjectPresignRequest.builder()
.signatureDuration(props.downloadTtl())
.getObjectRequest(o -> o.bucket(props.bucket()).key(a.key()))
.build();
return presigner.presignGetObject(request).url().toString();
}
The controller answers GET /api/attachments/{id} with 302 Found and the signed GET in Location, or 404 if there's no such attachment. A browser follows the redirect by itself. Here the link had X-Amz-Expires=300, and following it returned the file: 1887 bytes, the same bytes that were uploaded.
The same object's plain URL, without a signature, got 403 AccessDenied. The bucket has no public door. Each download gets a fresh link, so the API can check access every time before signing.
Break it: a 5-second link
The app was restarted with a download TTL of 5 seconds. The new link had X-Amz-Expires=5. Fetched at once: 200. Fetched again 7 seconds later: 403, Request has expired. A link copied into a chat or a log stops working on its own.
Two things outside the code
- CORS on the bucket. The browser's PUT goes to another origin (the bucket), so the bucket needs a CORS rule that allows
PUTfrom the app's origin with theContent-Typeheader. - The signer's permissions. The app's role needs
s3:PutObjectands3:GetObjecton this bucket's keys, and nothing more. A signed URL can never do more than the role that signed it.
Common mistakes
- Making the bucket public "just for downloads". Every file is then one guessed URL away.
- Letting the browser choose the key. It can overwrite other files. The API builds the key.
- Long expiry times. A link that works for a week works for whoever finds it. Minutes are enough.
- Storing the signed URL instead of the key. It expires. Store the key and sign again per download.
Try it yourself
Ask for an upload slip with contentType image/png, then PUT a file with Content-Type: image/jpeg. What does the store answer, and which part of the URL explains it?
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Why Spring in 2026: What the Container Does and What Spring Framework 7 Changed
Spring in one line: a container that creates your classes and hands each one what it needs. Plus the Spring Framework 7 baseline (JDK 17 to 25, Jakarta EE 11, Tomcat 11, JUnit 6), what got better than Spring 6, and a two-line version check.
A Plain Spring Project, No Boot: Your First Bean With spring-context
One dependency, one recipe, one getBean: a Maven project with spring-context 7.0.9, a Blog record, an AppConfig with @Bean, and a main that asks the container for the Blog. Then delete @Bean and meet NoSuchBeanDefinitionException.
Inversion of Control and Dependency Injection in Spring: One Program, Built Three Ways
A PostService needs a PostRepository. Build it three ways: the service calls new itself (tight coupling), main hands it in through the constructor (DI by hand), and the Spring container does the wiring from a @Configuration recipe.
Spring Component Scanning: @Component and @ComponentScan Instead of @Bean Methods
Instead of one @Bean method per class, put @Component on EmailNotifier and PostService and @ComponentScan on an empty BlogConfig. Spring walks the package, finds the stickers and builds the beans; main doesn't change.
