Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Spring Boot
  • Why Spring in 2026: What the Container Does and What Spring Framework 7 Changed
  • A Plain Spring Project, No Boot: Your First Bean With spring-context
  • Inversion of Control and Dependency Injection in Spring: One Program, Built Three Ways
  • Spring Component Scanning: @Component and @ComponentScan Instead of @Bean Methods
  • Spring Autowiring: Spring Fills the Constructor, and When @Autowired Is Needed
  • Two Beans, One Type: Spring @Primary and @Qualifier
  • Spring Bean Scopes: Singleton vs Prototype, One Shared Object or a Fresh One
  • Spring Stereotypes: @Service, @Repository and @Controller Are @Component With a Job Name
  • The Spring Bean Lifecycle: @PostConstruct and @PreDestroy
  • The Mini Blog Wired by Spring: Plain Java vs Spring, Side by Side
  • Spring MVC and SQLite Without Spring Boot: the Mini Blog in the Browser
  • Your First Spring Boot 4 Project: Create It in IntelliJ, Run It, and the Four Files That Matter
  • What Is Spring Boot? Spring Framework 7 With the Decisions Already Made
  • The Project Context File: AGENTS.md and CLAUDE.md for a Spring Boot Project
  • Plan Before Code: a Five-Part Brief, Plan Mode and /goal for a Spring Boot Feature
  • From Design Frames to Thymeleaf Pages: Briefing an AI Agent for a Spring Boot Blog
  • Add, Edit and Delete Posts With a Rich-Text Editor in Spring Boot: Quill, jsoup and th:utext
  • Profile Page and Photo Upload in Spring Boot: Check the File, Shrink It, Keep Your Own Name
  • Building a Feature With an AI Agent, End to End: Comments on a Spring Boot Blog
  • Containerising Spring Boot: a Layered Dockerfile vs Buildpacks
  • GraalVM Native Image and Spring AOT: When It Pays, and What It Costs
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Scheduled Jobs in Spring Boot: fixedRate, fixedDelay, cron, and ShedLock for Many Instances
  • Redis in Spring Boot: a Cache, a Rate-Limit Counter and a Job Status Hash
  • Actuator and Micrometer in Spring Boot: Health, Your Own Metrics, and the Four Numbers That Matter
  • Structured Logging and Correlation IDs in Spring Boot: JSON Lines, a Filter and the MDC
  • Dashboards and Alerts for a Spring Boot App: Prometheus, Grafana and One Real Incident
  • Finding a Slow Spring Boot Endpoint: Actuator Timers, EXPLAIN ANALYZE and One Index
  • A GitHub Actions Workflow for a Maven Project: Cache, a Java Matrix and Test Reports That Survive a Red Run
  • The AWS SDK for Java v2 in Spring Boot: Clients as Beans, the Default Credentials Chain and No Keys in Code
  • Attachments in S3 from Spring Boot: Pre-signed Uploads, a 302 to a Pre-signed Download, and Links That Expire
  • CloudWatch for a Spring Boot App: JSON Logs, Micrometer Metrics From Your Own Code, and an Alarm That Reaches a Person
  • Automated Deploy, Smoke Test and Rollback for a Spring Boot App: Green Tests Are Not a Working Deploy
  • Environments, Secrets and Approvals in GitHub Actions: One Image From Staging to Production
  • Distributed Tracing Across Spring Boot Services and Kafka: One Trace ID From the Gateway to the Last Reader, Even Through an Outbox
  • Thymeleaf and htmx in Spring Boot: Live Search and One-Row Updates From Server-Rendered Fragments, With No JavaScript Framework
  • Rate Limiting, Backpressure and Load Shedding in Spring Boot: Bucket4j in Redis, a Bounded Worker Pool and Dropping Low-Priority Work
  • Resilience4j in Spring Boot: A Timeout, One Retry, a Circuit Breaker, a Bulkhead and a Fallback, Measured Against a Slow Dependency
  • Spring Boot Repository and Service Layer: Save and Read Data Without Writing SQL
  • Entities and H2 in Spring Boot: a Post Class Becomes a Table
  • Seed Data and Posts on the Homepage: CommandLineRunner, the Model and th:each
  • Pagination and Sorting on a Spring Boot Homepage: PageRequest In, Page Out
  • Connect Spring Boot to PostgreSQL: Driver, application.yml and the Hikari Pool
  • JPA Entity Mapping: Ids, Enums and Dates, From a Java Class to a Table
  • Spring Data Query Methods: Derived Queries, @Query and Projections
  • The N+1 Problem in JPA: Fetch Types, Join Fetch and Entity Graphs
  • Spring @Transactional: All or Nothing, the Proxy, and the Self-Call Trap
  • Flyway Migrations in Spring Boot: Numbered SQL Files, Seed Data and the History Table
  • Spring Data JPA Auditing and Soft Deletes: Who Changed It, When, and Hiding Instead of Deleting
  • Optimistic Locking with @Version: Two Agents, One Ticket, No Lost Update
  • Finding a Slow Spring Boot Endpoint: Actuator Timers, EXPLAIN ANALYZE and One Index
  • Caching With Spring and Redis: Cache-Aside, a TTL per Kind of Data, Eviction on Edit and Stopping the Stampede
  • A PostgreSQL Read Replica in Spring Boot: Route readOnly Transactions, Size the Pool, Find the Index, Read Your Own Writes
  • A Registration Form With Bean Validation in Spring Boot: @Valid, BindingResult and th:errors
  • Spring Security 7 Form Login, BCrypt and a UserDetailsService on the Account Table
  • Roles and Authorities at Login in Spring Security: From a ROLE Column to hasRole("ADMIN")
  • Menus per Role With Thymeleaf Security Tags: sec:authorize, sec:authentication and an Edit Button for the Author
  • Fixing the Access Bugs: a Rule per Role and an Ownership Check in Spring Security
  • Add, Edit and Delete Posts With a Rich-Text Editor in Spring Boot: Quill, jsoup and th:utext
  • Remember Me and Forgot Password by Email in Spring Boot: a Signed Cookie and a One-Time Link
  • Spring Boot Security Defaults: What One Dependency Gives You for Free
  • The Spring Security Filter Chain and Your Own Rules: 401, 403 and Rule Order
  • Stateless JWT Authentication in Spring Security: Sign Once, Check Every Request
  • Users in the Database with Spring Security: Register, BCrypt and Log In
  • Method Security in Spring: @PreAuthorize, Roles and Who Owns This Ticket
  • CORS and CSRF in Spring Security: Why the Browser Blocks Your SPA, and When CSRF Can Be Off
  • Reviewing AI-Written Spring Code for Security: Four Questions for Every Diff
  • Testing Secured Endpoints in Spring Boot: 401, 403 and 200 with @WithMockUser
  • An API Gateway With Spring Cloud Gateway: Check the JWT Once at the Edge, Pass the Caller Inward, and Know What the Network Now Trusts
  • Unit Tests With AI for a Spring Boot Service: Mockito Mocks, Given-When-Then and a Green Run
  • Docker for a Spring Boot App: Run the Tests in the Image Build, or Skip Them on Purpose
  • The Test Pyramid in Spring Boot: Unit, Slice and Whole-App Tests
  • Mockito and Test Doubles: Stubs, Mocks and Fakes for One Java Class
  • Spring Boot Test Slices: @WebMvcTest with MockMvc and @DataJpaTest
  • Integration Tests with Testcontainers: A Real PostgreSQL for Every Spring Boot Test Run
  • Testing Secured Endpoints in Spring Boot: 401, 403 and 200 with @WithMockUser
  • Test-First with a Coding Agent: Spec, Red Tests, Then the Code
  • Quality and Security Gates for a Maven Project: JaCoCo Coverage, PMD, an SBOM and a Trivy Scan
  • Testing Spring AI Features: a Stub ChatModel, Must-Cite and Must-Refuse Tests, and One Tagged Model Test
  • What Spring AI 2 Is, and Why a Java Team Wants It
  • Spring AI ChatClient: One API for Any Model, and the Model Is a Property
  • Spring AI Prompt Templates: Placeholders, Few-Shot Messages and Versioned Prompt Files
  • Spring AI Structured Output: From Model JSON to a Java Record, and a Real Ticket Triage Feature
  • Streaming Spring AI Answers to the Browser: stream(), a Flux of Server-Sent Events and the Cancel
  • Local Models With Ollama in Spring AI: Profiles, Per-Call Options and What a Smaller Model Costs
  • Testing Spring AI Features: a Stub ChatModel, Must-Cite and Must-Refuse Tests, and One Tagged Model Test
  • Embeddings and pgvector in Spring AI: EmbeddingModel, VectorStore, Distance Operators and the HNSW Index
  • RAG Ingestion in Spring AI: Parse Markdown, Chunk by Section, Embed Into pgvector With Stable Ids
  • Tuning Retrieval in Spring AI: Top-k, a Minimum Score, a Tenant Filter Inside the Query, Hybrid Search and a Reranker
  • Tool Calling in Spring AI 2: @Tool Methods, the ToolCallingAdvisor Loop and a Tool-Call Limit
  • Chat Memory in Spring AI: MessageChatMemoryAdvisor, a Conversation Id, a Window, a Summary and Where the State Lives
  • Building an MCP Server in Java With Spring AI: @McpTool, Stateless Streamable HTTP and Least-Privilege Tools
  • Consuming MCP Servers From Spring AI: a stdio Child Process and a Remote Streamable HTTP Server, Compared
  • A Supervisor and Specialist Agents in Spring AI: Own Prompts, Own Tools, Explicit State and a Menu Checked in Code
  • Choosing a JVM Agent Framework: the Same Two-Step Triage in Spring AI, LangChain4j Agentic and Embabel
  • Observability for Spring AI Calls: a Span per Feature, Token and Spend Counters, Jaeger Traces and Two Prometheus Alerts
  • Evals and Cost Control for a Java Subtitle Service: A Golden Set Scored by Word Error Rate in CI, and the Cost of One Hour of Audio From Micrometer Meters
  1. Blog
  2. /
  3. Spring Boot
  4. /
  5. Fundamentals

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Fundamentals

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 browser asks the API for an upload slip and gets a signed PUT URL valid for 600 seconds. The browser uploads the file straight to the private bucket with that URL. The browser confirms the key to the API, which records it. For a download, the API answers 302 with a signed GET valid for 300 seconds, and the browser fetches the file from the bucket. browserReact app Relay APIsigns, never stores bytes private bucketno public access 1 upload-url: signed PUT, 600 s 2 PUT the file, straight to S3 3 confirm the key 4 download: 302 to a signed GET, 300 s
The API hands out permission. The file goes between the browser and the bucket.

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:

ParameterMeaning
X-Amz-Algorithm=AWS4-HMAC-SHA256how it was signed
X-Amz-Credentialwhose key signed it (an access key id and a scope, never the secret)
X-Amz-Date, X-Amz-Expires=600when it was signed, and for how many seconds it works
X-Amz-SignedHeaders=content-type;hostheaders that must match, so the PUT has to send image/png
X-Amz-Signaturethe 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 PUT from the app's origin with the Content-Type header.
  • The signer's permissions. The app's role needs s3:PutObject and s3:GetObject on 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?

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Spring Boot · 33 of 99

Previous
The AWS SDK for Java v2 in Spring Boot: Clients as Beans, the Default Credentials Chain and No Keys in Code
Next post
CloudWatch for a Spring Boot App: JSON Logs, Micrometer Metrics From Your Own Code, and an Alarm That Reaches a Person

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.

On this page

  • Three arrows
  • The signer
  • Step 1: an upload slip
  • What's in a signed URL
  • Step 2 and 3: upload, then confirm
  • Step 4: download with a 302
  • Break it: a 5-second link
  • Two things outside the code
  • Common mistakes
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.