Google OAuth2.0+Lambda+S3授权-如何引用S3中的文件



我正试图使用谷歌的身份验证,但我对如何在方法中使用有疑问:

GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream("MyProject-1234.json"))
.createScoped(Collections.singleton(SQLAdminScopes.SQLSERVICE_ADMIN));

文件MyProject-1234.json存储在一个S3 bucket上,而它目前正在lambda中运行,我如何在身份验证中使用该文件?我不确定我是否应该发送路径和方式,或者我是否应该做其他事情。

您需要使用AWS SDK for Java将文件从S3下载到Lambda函数的本地文件系统。不能使用FileInputStream打开S3对象,只能使用它打开本地文件系统对象。

以下是如何从S3中提取文件并使用它。

简而言之,getFileFromS3(...)方法将返回一个可用于创建FileInputStreamFile对象。

public class S3FileTest implements RequestStreamHandler {
private LambdaLogger logger;
@Override
public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException {
logger = context.getLogger();
String bucketName = "==== S3 BUCKET NAME ====";
String fileName = "==== S3 FILE NAME ====";
File localFile = getFileFromS3(context, bucketName, fileName);
if(localFile == null) {
// handle error
// return ....
}
// use the file
GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(localFile))
.createScoped(Collections.singleton(SQLAdminScopes.SQLSERVICE_ADMIN));

// do more
// ...
}
private File getFileFromS3(Context context, String bucketName, String fileName) {
AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(Regions.US_EAST_1).build();
// s3 client
if (s3Client == null) {
logger.log("S3 Client is null - can't continue!");
return null;
}
// s3 bucket - make sure it exist
if (!s3Client.doesBucketExistV2(bucketName)) {
logger.log("S3 Bucket does not exists - can't continue!");
return null;
}

File localFile = null;
try {
localFile = File.createTempFile(fileName, "");
// get S3Object
S3Object s3Object = s3Client.getObject(bucketName, fileName);
// get stream from S3Object
InputStream inputStream = s3Object.getObjectContent();
// write S3Object stream into a temp file
Files.copy(inputStream, localFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
return localFile;
} catch (Exception e) {
logger.log("Failed to get file from S3: " + e.toString());
return null;
}
}
}

最新更新