Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Building a Secure File Upload Service with Spring Boot and JWT Authentication

Tech May 14 1

In modern web applications, file upload functionality serves as a critical component for various use cases. This article demonstrates how to implement a robust and secure file upload service using Spring Boot, handling batch uploads, JWT-based authentication, and persistent storage.

Service Implementation

The core upload logic resides in the service implementation class FileUploadServiceImpl, which implements the FileUploadService interface. This class injects HttpServletRequest to extract JWT tokens from incoming requests, parsing user identifiers using the Hutool library to associate uploaded files with atuhenticated users.

Required Dependencies

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.24</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <scope>provided</scope>
</dependency>

FileUploadController - REST Controller

@Slf4j
@RestController
@RequestMapping("/api/upload")
public class FileUploadController {

    @Autowired
    private FileUploadService fileUploadService;

    /**
     * Handles multipart file upload requests via HTTP POST.
     *
     * @param files Array of files submitted by the client
     * @return Response containing upload status and file URLs
     */
    @PostMapping
    public ResponseEntity<ApiResponse<List<String>>> uploadFiles(
            @RequestParam("files") MultipartFile[] files) {
        try {
            List<String> uploadedUrls = fileUploadService.processUpload(files);
            if (uploadedUrls != null && !uploadedUrls.isEmpty()) {
                return ResponseEntity.ok(ApiResponse.success(uploadedUrls));
            }
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("Upload failed"));
        } catch (FileUploadException e) {
            log.error("Upload error: {}", e.getMessage());
            return ResponseEntity.status(500)
                    .body(ApiResponse.error("Upload failed: " + e.getMessage()));
        } catch (Exception e) {
            log.error("Unexpected error during upload: {}", e.getMessage());
            return ResponseEntity.status(500)
                    .body(ApiResponse.error("Unexpected error occurred"));
        }
    }
}

FileUploadService - Service Interface

/**
 * Service interface for handling file upload operations.
 */
public interface FileUploadService {

    /**
     * Processes batch file uploads and returns URLs for successfully saved files.
     *
     * @param files Array of MultipartFile objects to upload
     * @return List of accessible URLs for uploaded files
     */
    List<String> processUpload(MultipartFile[] files);
}

FileUploadServiceImpl - Service Implementation

@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private FileStorageRepository fileStorageRepository;

    @Value("${upload.base-path:/var/uploads}")
    private String uploadBasePath;

    @Value("${upload.base-url:http://localhost:8080/files}")
    private String baseUrl;

    private static final long MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
    private static final String[] ALLOWED_TYPES = {"image/jpeg", "image/png", "application/pdf"};

    @Override
    public List<String> processUpload(MultipartFile[] files) {
        if (files == null || files.length == 0) {
            throw new IllegalArgumentException("No files provided");
        }

        Long userId = extractUserIdFromToken();
        List<String> uploadedUrls = new ArrayList<>();

        for (MultipartFile file : files) {
            validateFile(file);
            String storedPath = saveFile(file, userId);
            String accessUrl = generateAccessUrl(storedPath);
            persistFileMetadata(file, userId, storedPath, accessUrl);
            uploadedUrls.add(accessUrl);
        }

        log.info("User {} uploaded {} files successfully", userId, uploadedUrls.size());
        return uploadedUrls;
    }

    private Long extractUserIdFromToken() {
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            throw new SecurityException("Invalid or missing authentication token");
        }

        String token = authHeader.substring(7);
        Claims claims = JwtUtil.parseToken(token);
        return Long.valueOf(claims.getSubject());
    }

    private void validateFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new FileValidationException("File is empty");
        }
        if (file.getSize() > MAX_FILE_SIZE) {
            throw new FileValidationException("File exceeds maximum size of 10MB");
        }
        if (!isAllowedContentType(file.getContentType())) {
            throw new FileValidationException("File type not permitted: " + file.getContentType());
        }
    }

    private boolean isAllowedContentType(String contentType) {
        return Arrays.stream(ALLOWED_TYPES)
                .anyMatch(type -> type.equals(contentType));
    }

    private String saveFile(MultipartFile file, Long userId) {
        String filename = generateUniqueFilename(file.getOriginalFilename());
        Path userDir = Paths.get(uploadBasePath, String.valueOf(userId));

        try {
            Files.createDirectories(userDir);
            Path targetPath = userDir.resolve(filename);
            file.transferTo(targetPath);
            return targetPath.toString();
        } catch (IOException e) {
            log.error("Failed to save file: {}", e.getMessage());
            throw new FileStorageException("Unable to persist file", e);
        }
    }

    private String generateUniqueFilename(String originalFilename) {
        String extension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        return UUID.randomUUID().toString() + extension;
    }

    private String generateAccessUrl(String storedPath) {
        Path path = Paths.get(storedPath);
        String relativePath = path.getFileName().toString();
        return baseUrl + "/" + relativePath;
    }

    private void persistFileMetadata(MultipartFile file, Long userId, 
            String storedPath, String accessUrl) {
        FileMetadata metadata = new FileMetadata();
        metadata.setOriginalName(file.getOriginalFilename());
        metadata.setStoredPath(storedPath);
        metadata.setAccessUrl(accessUrl);
        metadata.setSize(file.getSize());
        metadata.setContentType(file.getContentType());
        metadata.setUserId(userId);
        metadata.setUploadTime(LocalDateTime.now());

        fileStorageRepository.save(metadata);
    }
}

FileMetadata Entity

@Entity
@Table(name = "file_metadata")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class FileMetadata {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String originalName;

    @Column(nullable = false)
    private String storedPath;

    @Column(nullable = false)
    private String accessUrl;

    private Long size;

    private String contentType;

    @Column(nullable = false)
    private Long userId;

    private LocalDateTime uploadTime;

    @PrePersist
    protected void onCreate() {
        if (uploadTime == null) {
            uploadTime = LocalDateTime.now();
        }
    }
}

Configuration Properties

# application.yml
spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 50MB

upload:
  base-path: /var/uploads
  base-url: http://localhost:8080/api/files

Key Sceurity Considerations

  • JWT token validation ensures only authenticated users can upload files
  • Content type validation prevents malicious file uploads
  • File size limits protect against denial-of-service attacks
  • User-specific storage directories provide logical isolation
  • Metadata persistence enables audit trails and retrieval operations

Database Schema

CREATE TABLE file_metadata (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    original_name VARCHAR(255) NOT NULL,
    stored_path VARCHAR(500) NOT NULL,
    access_url VARCHAR(500) NOT NULL,
    size BIGINT,
    content_type VARCHAR(100),
    user_id BIGINT NOT NULL,
    upload_time DATETIME,
    INDEX idx_user_id (user_id),
    INDEX idx_upload_time (upload_time)
);

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.