728x90
1. AWS SDK 의존성 추가
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>s3</artifactId>
<version>2.20.125</version>
</dependency>
2. application.yml 추가
aws:
s3:
bucket-name: {bucketName}
endpoint: {endPoint}
3. 컨트롤러
@GetMapping("/generate-presigned-url")
public String generatePresignedUrl(@RequestParam String fileName) {
URL url = s3Service.generatePresignedUrl(fileName);
return url.toString();
}
4. 서비스 코드
@Service
public class S3Service {
@Autowired
private S3Presigner s3presigner;
@Value("${aws.s3.bucket-name}")
private String s3_bucket_name;
@Value("${aws.s3.endpoint}")
private String s3_endpoint;
public URL generatePresignedUrl(String objectKey) {
PutObjectRequest putObjectRequest = PutObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
.build();
PutObjectPresignRequest presignRequest = PutObjectPresignRequest.builder()
.signatureDuration(Duration.ofMinutes(10)) // URL 유효시간 설정
.putObjectRequest(putObjectRequest)
.build();
return s3Presigner.presignPutObject(presignRequest).url();
}
}
이렇게해서 생성된 url에 PUT으로 파일을 올려주면 성공
+) accesskey를 세팅하지 않아도 되는 이유
S3Presigner 라이브러리를 사용 중인데, 내부를 살펴보면 credential을 DefaultCredentialsProvider에서 가져온다는 것을 알 수 있다.
DefaultCredentialsProvider는 알아서 키를 세팅하는데 방법은 아래와 같다
- Java System Properties - aws.accessKeyId and aws.secretAccessKey
- Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
- Web Identity Token credentials from system properties or environment variables
- Credential profiles file at the default location (~/.aws/credentials) shared by all AWS SDKs and the AWS CLI
- Credentials delivered through the Amazon EC2 container service if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" environment variable is set and security manager has permission to access the variable,
- Instance profile credentials delivered through the Amazon EC2 metadata service
reference
728x90
'Backend 🧦' 카테고리의 다른 글
HTTP X- 헤더 (0) | 2024.08.19 |
---|---|
Spring Cloud(Gateway) (1) | 2024.08.14 |
[AWS/Lambda] aws console에서 lambda 함수 다운받기 (0) | 2024.05.24 |
[Java] Boolean vs boolean (0) | 2024.05.11 |
[Spring] 스프링 스케줄러(Spring Scheduler) (0) | 2023.11.14 |
댓글