googleoauth2.0+lambda+s3授权-如何从s3引用文件?

8fsztsew  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(281)

我正在尝试使用来自谷歌的身份验证,但是我对如何使用该方法有疑问:

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

myproject-1234.json文件存储在一个s3 bucket中,这个文件当前正在lambda中运行,如何在身份验证中使用这个文件?我不确定我是否应该发送路径以及如何发送,或者我是否应该做其他事情。

zzzyeukh

zzzyeukh1#

下面是如何从s3中提取文件并使用它。
简而言之 getFileFromS3(...) 方法将返回 File 可以用来创建 FileInputStream .

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;
        }
    }
}
kuhbmx9i

kuhbmx9i2#

您需要首先使用awsdkforjava将文件从s3下载到lambda函数的本地文件系统。你不能使用 FileInputStream 要打开s3对象,只能使用它打开本地文件系统对象。

相关问题