Spring Boot Amazon AWS S3存储桶文件下载-访问被拒绝

我有一个自动配置的AWS,Spring Boot" title="Spring Boot">Spring Boot应用程序,并且我试图设置一个端点,该端点将简单地从Amazon

S3中给定存储桶中下载特定文件。我使用AWS控制台从计算机上将JPEG文件上传到存储桶中-现在,我正尝试使用Spring Boot API下载该文件。

我收到以下错误: com.amazonaws.services.s3.model.AmazonS3Exception: Access Denied

(Service: Amazon S3; Status Code: 403; Error Code: AccessDenied;

我已经在AWS控制台上创建了一个用户和一个组(该组中的用户)。用户/组具有对S3的完全访问权限以及管理员访问权限。我下载了access-key /

secret-key对,并出于测试目的,将这些字面值确实粘贴到了我的application.properties文件中,如下所示(显然这里没有显示键:))。

我很困惑为什么我仍然拒绝访问。我已经搜索和处理了一段时间;我似乎找不到特定于Spring Boot的解决方案。任何帮助将不胜感激。

application.properties:

cloud.aws.credentials.accessKey=myaccesskey

cloud.aws.credentials.secretKey=mysecretkey

cloud.aws.credentials.instanceProfile=false

cloud.aws.stack.auto=false

cloud.aws.region.auto=true

cloud.aws.region.static=myregion

SimpleResourceLoadingBean.java:

@RestController

public class SimpleResourceLoadingBean {

private static Logger log = LoggerFactory.getLogger(HealthMonitorApplication.class);

@Autowired

private ResourceLoader resourceLoader;

@RequestMapping("/getresource")

public String resourceLoadingMethod() throws IOException {

log.info("IN RESOURCE LOADER");

Resource resource = this.resourceLoader.getResource("s3://s3.amazonaws.com/mybucket/myfile.ext");

InputStream inputStream = resource.getInputStream();

return inputStream.toString();

}

}

pom.xml(仅与问题相关的依赖项)

        <dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-aws</artifactId>

<version>1.1.0.RELEASE</version>

</dependency>

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-aws-autoconfigure</artifactId>

<version>1.1.0.RELEASE</version>

</dependency>

回答:

找出解决方案。除了application.properties配置之外,我还必须创建一个配置类,当提供适当的凭证时,该类将使我能够访问AmazonS3Client对象。我在GitHub上遵循了以下示例:

https://github.com/brant-hwang/spring-cloud-aws-

example/blob/master/src/main/java/com/axisj/spring/cloud/aws/AWSConfiguration.java

AWSConfiguration.java:

import com.amazonaws.auth.AWSCredentials;

import com.amazonaws.auth.BasicAWSCredentials;

import com.amazonaws.regions.Region;

import com.amazonaws.regions.Regions;

import com.amazonaws.services.s3.AmazonS3Client;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

public class AWSConfiguration {

@Value("${cloud.aws.credentials.accessKey}")

private String accessKey;

@Value("${cloud.aws.credentials.secretKey}")

private String secretKey;

@Value("${cloud.aws.region}")

private String region;

@Bean

public BasicAWSCredentials basicAWSCredentials() {

return new BasicAWSCredentials(accessKey, secretKey);

}

@Bean

public AmazonS3Client amazonS3Client(AWSCredentials awsCredentials) {

AmazonS3Client amazonS3Client = new AmazonS3Client(awsCredentials);

amazonS3Client.setRegion(Region.getRegion(Regions.fromName(region)));

return amazonS3Client;

}

}

配置完成后,您可以在其他类中创建AmazonS3Client对象(自动装配),并使用客户端向您的S3云发出请求。该示例将包装器类用作服务,以简化其他控制器类的实现。

S3Wrapper.java:

import com.amazonaws.services.s3.AmazonS3Client;

import com.amazonaws.services.s3.model.*;

import org.apache.commons.io.IOUtils;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.http.HttpHeaders;

import org.springframework.http.HttpStatus;

import org.springframework.http.MediaType;

import org.springframework.http.ResponseEntity;

import org.springframework.stereotype.Service;

import org.springframework.util.StringUtils;

import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStream;

import java.net.URLEncoder;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

@Service

public class S3Wrapper {

@Autowired

private AmazonS3Client amazonS3Client;

@Value("${cloud.aws.s3.bucket}")

private String bucket;

private PutObjectResult upload(String filePath, String uploadKey) throws FileNotFoundException {

return upload(new FileInputStream(filePath), uploadKey);

}

private PutObjectResult upload(InputStream inputStream, String uploadKey) {

PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, uploadKey, inputStream, new ObjectMetadata());

putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead);

PutObjectResult putObjectResult = amazonS3Client.putObject(putObjectRequest);

IOUtils.closeQuietly(inputStream);

return putObjectResult;

}

public List<PutObjectResult> upload(MultipartFile[] multipartFiles) {

List<PutObjectResult> putObjectResults = new ArrayList<>();

Arrays.stream(multipartFiles)

.filter(multipartFile -> !StringUtils.isEmpty(multipartFile.getOriginalFilename()))

.forEach(multipartFile -> {

try {

putObjectResults.add(upload(multipartFile.getInputStream(), multipartFile.getOriginalFilename()));

} catch (IOException e) {

e.printStackTrace();

}

});

return putObjectResults;

}

public ResponseEntity<byte[]> download(String key) throws IOException {

GetObjectRequest getObjectRequest = new GetObjectRequest(bucket, key);

S3Object s3Object = amazonS3Client.getObject(getObjectRequest);

S3ObjectInputStream objectInputStream = s3Object.getObjectContent();

byte[] bytes = IOUtils.toByteArray(objectInputStream);

String fileName = URLEncoder.encode(key, "UTF-8").replaceAll("\\+", "%20");

HttpHeaders httpHeaders = new HttpHeaders();

httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);

httpHeaders.setContentLength(bytes.length);

httpHeaders.setContentDispositionFormData("attachment", fileName);

return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);

}

public List<S3ObjectSummary> list() {

ObjectListing objectListing = amazonS3Client.listObjects(new ListObjectsRequest().withBucketName(bucket));

List<S3ObjectSummary> s3ObjectSummaries = objectListing.getObjectSummaries();

return s3ObjectSummaries;

}

}

注意:为了使用Apache Commons IO库,需要将以下依赖项添加到pom.xml中。

pom.xml:

<dependency>

<groupId>org.apache.commons</groupId>

<artifactId>commons-io</artifactId>

<version>1.3.2</version>

</dependency>

以上是 Spring Boot Amazon AWS S3存储桶文件下载-访问被拒绝 的全部内容, 来源链接: utcz.com/qa/433312.html

回到顶部