S3AsyncClient-删除授权标头

如何解决S3AsyncClient-删除授权标头

我正在尝试使用S3AsyncClient下载具有预签名URL的S3对象。但是,该请求仍会带有Authorization标头,其中包括使用与该特定S3实例(这是模拟AWS S3对象存储的Enterprise S3实例)不兼容的密码生成的签名。这将导致SSLException。当我在浏览器中或通过没有授权标头的邮递员发送请求时,URL有效。

我可以通过S3AsyncClient通过未经授权,x-amz-content-sha256和X-Amz-日期标头发送带有预签名URL的这种GET请求吗?

登录预签名URL:

Generating pre-signed URL.
Pre-Signed URL: https://<namespace>.<endpoint>/<bucket>/<key>?AWSAccessKeyId=<access-id>01&Expires=1600801209&Signature=......../..................=

HTTP请求的调试日志如下所示(我将注意到,预先签名的URL中的签名参数现在已编码并放置在其他参数之前,尽管在提取URL并发送GET请求时这似乎无关紧要):

GET /<bucket>/VADRUserGuide.docx?Signature=........%2F..................%3D&AWSAccessKeyId=<access-id>&Expires=1600801209 HTTP/1.1
Host: <namespace>.<endpoint>
amz-sdk-invocation-id: ........-....-....-....-............
amz-sdk-retry: 3/152/440
Authorization: AWS4-HMAC-SHA256 Credential=access-id>/20200922/us-east-1/s3/aws4_request,SignedHeaders=amz-sdk-invocation-id;amz-sdk-retry;authorization;host;x-amz-content-sha256;x-amz-date,Signature=.................................................
User-Agent: aws-sdk-java/2.10.86 Windows_10/10.0 Java_HotSpot_TM__64-Bit_Server_VM/25.191-b12 Java/1.8.0_191 vendor/Oracle_Corporation io/async http/UNKNOWN
x-amz-content-sha256: UNSIGNED-PAYLOAD
X-Amz-Date: 20200922T213232Z)

DownloadResource(源-https://github.com/eugenp/tutorials/blob/master/aws-reactive/src/main/java/com/baeldung/aws/reactive/s3/DownloadResource.java):

/**
 * @author Philippe
 *
 */
@RestController
@RequestMapping("/inbox")
@Slf4j
public class DownloadResource {

    private final GeneratePresignedURL generatePresignedURL;
    private final S3AsyncClient s3client;
    private final S3ClientConfigurationProperties s3config;

    public DownloadResource(S3AsyncClient s3client,S3ClientConfigurationProperties s3config,GeneratePresignedURL generatePresignedURL) {
        this.s3client = s3client;
        this.s3config = s3config;
        this.generatePresignedURL = generatePresignedURL;
    }


    @GetMapping(path="/{filekey}")
    public Mono<ResponseEntity<Flux<ByteBuffer>>> downloadFile(@PathVariable("filekey") String filekey) {
        //generate pre-signed URL
        final String url = generatePresignedURL.getPresignedUrl(filekey);

        //extract signed URL params
        final String pattern = "(\\?|\\&)([^=]+)\\=([^&]+)";
        List<String> params = new ArrayList<>();
        Matcher m = Pattern.compile(pattern)
                .matcher(url);
        while (m.find()) {
            params.add(m.group());
        }
        final String[] p0 = params.get(0).substring(1).split("=",2);
        final String[] p1 = params.get(1).substring(1).split("=",2);
        final String[] p2 = params.get(2).substring(1).split("=",2);

        //attach signed URL params via AwsRequestOverrideConfiguration
        AwsRequestOverrideConfiguration overrideConfiguration = AwsRequestOverrideConfiguration.builder()
                .putRawQueryParameter(p0[0],p0[1])
                .putRawQueryParameter(p1[0],p1[1])
                .putRawQueryParameter(p2[0],p2[1])
                .build();
        GetObjectRequest request = GetObjectRequest.builder()
                .key(filekey)
                .overrideConfiguration(overrideConfiguration)
                .bucket(s3config.getBucket())
                .build();
        return Mono.fromFuture(s3client.getObject(request,new FluxResponseProvider()))
                .map( (response) -> {
                    checkResult(response.sdkResponse);
                    String filename = getMetadataItem(response.sdkResponse,"filename",filekey);

                    log.info("[I65] filename={},length={}",filename,response.sdkResponse.contentLength() );

                    return ResponseEntity.ok()
                            .header(HttpHeaders.CONTENT_TYPE,response.sdkResponse.contentType())
                            .header(HttpHeaders.CONTENT_LENGTH,Long.toString(response.sdkResponse.contentLength()))
                            .header(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename=\"" + filename + "\"")
                            .body(response.flux);
                });
    }
    private void printRequestFields(GetObjectRequest request){
        System.out.println("request fields:");
        String[] parValues = new String[6];

        Field[] fields = request.getClass().getDeclaredFields();

        //print field names paired with their values
        for ( Field field : fields  ) {
            try {
                field.setAccessible(true);
                System.out.println( field.getName() +": ");
                //requires access to private field:
                System.out.println( field.get(request) );
            } catch ( IllegalAccessException ex ) {
                System.out.println(ex);
            }
        }
    }

    /**
     * Lookup a metadata key in a case-insensitive way.
     * @param sdkResponse
     * @param key
     * @param defaultValue
     * @return
     */
    private String getMetadataItem(GetObjectResponse sdkResponse,String key,String defaultValue) {
        for( Entry<String,String> entry : sdkResponse.metadata().entrySet()) {
            if ( entry.getKey().equalsIgnoreCase(key)) {
                return entry.getValue();
            }
        }
        return defaultValue;
    }


    // Helper used to check return codes from an API call
    private static void checkResult(GetObjectResponse response) {
        SdkHttpResponse sdkResponse = response.sdkHttpResponse();
        if ( sdkResponse != null && sdkResponse.isSuccessful()) {
            return;
        }

        throw new DownloadFailedException(response);
    }


    static class FluxResponseProvider implements AsyncResponseTransformer<GetObjectResponse,FluxResponse> {

        private FluxResponse response;

        @Override
        public CompletableFuture<FluxResponse> prepare() {
            response = new FluxResponse();
            return response.cf;
        }

        @Override
        public void onResponse(GetObjectResponse sdkResponse) {
            this.response.sdkResponse = sdkResponse;
        }

        @Override
        public void onStream(SdkPublisher<ByteBuffer> publisher) {
            response.flux = Flux.from(publisher);
            response.cf.complete(response);
        }

        @Override
        public void exceptionOccurred(Throwable error) {
            response.cf.completeExceptionally(error);
        }

    }

    /**
     * Holds the API response and stream
     * @author Philippe
     */
    static class FluxResponse {

        final CompletableFuture<FluxResponse> cf = new CompletableFuture<>();
        GetObjectResponse sdkResponse;
        Flux<ByteBuffer> flux;
    }

}

S3AsyncClient的配置(如您所见,凭据提供程序已被注释掉):

@Configuration
@EnableConfigurationProperties(S3ClientConfigurationProperties.class)
public class S3ClientConfiguration {

    @Bean
    public S3AsyncClient s3client(S3ClientConfigurationProperties s3props) {

        SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                .writeTimeout(Duration.ZERO)
                .maxConcurrency(64)
                .build();

        S3Configuration serviceConfiguration = S3Configuration.builder()
                .checksumValidationEnabled(false)
                .chunkedEncodingEnabled(true)
                .build();

        S3AsyncClientBuilder b = S3AsyncClient.builder()
                .httpClient(httpClient)
                .region(s3props.getRegion())
// credentials provider commented out
                .serviceConfiguration(serviceConfiguration);

        if (s3props.getEndpoint() != null) {
            b = b.endpointOverride(s3props.getEndpoint());
        }

        return b.build();
    }


// credentials provider Bean commented out


}

常规AmazonS3客户端的客户端(用于GeneratePresignedUrlRequest):


@Configuration
public class S3Configuration {

    @Bean
    public S3Storage s3Storage(S3ServiceInfo s3ServiceInfo) {
        final ClientConfiguration httpsClientConfig = new ClientConfiguration().withProtocol(Protocol.HTTPS).withSignerOverride("S3SignerType");
        SSLContext sslContext = SSLContexts.createSystemDefault();
        httpsClientConfig.getApacheHttpClientConfig().setSslSocketFactory(new SSLConnectionSocketFactory(sslContext));

        AmazonS3 client = AmazonS3ClientBuilder.standard()
            .withPathStyleAccessEnabled(true)
            .withForceGlobalBucketAccessEnabled(true)
            .withClientConfiguration(httpsClientConfig)
            .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(s3ServiceInfo.getAccessKey(),s3ServiceInfo.getSecretKey())))
            .withEndpointConfiguration(new EndpointConfiguration(endpointUrlWithNamespace(s3ServiceInfo.getEndpoint(),s3ServiceInfo.getAccessKey()),null))
            .build();

        return new S3Storage(client,s3ServiceInfo.getBucket(),s3ServiceInfo.getEndpoint());
    }

    protected String endpointUrlWithNamespace(String endpoint,String accessKey) {
        //extract namespace from access-key (verify format)
        Matcher matcher = Pattern.compile("((.+?-){3}ns\\d\\d)-").matcher(accessKey);
        if (!matcher.find()) return endpoint;
        String namespace = matcher.group(1);

        return endpoint.contains("://s3") ? endpoint.replace("://","://" + namespace + ".") : endpoint;
    }


    @Configuration
    public class S3LocalConfiguration {
        @Bean
        public S3ServiceInfo s3ServiceInfo(
                @Value("${s3.accessKey}") String accessKey,@Value("${s3.secretKey}") String secretKey,@Value("${s3.bucket}") String bucket,@Value("${s3.endpoint}") String endpoint) {

            return new S3ServiceInfo(null,accessKey,secretKey,endpoint,bucket);
        }
    }

    @Data
    @AllArgsConstructor
    public static class S3Storage {
        private AmazonS3 client;
        private String bucket;
        private String endpoint;
    }
}


版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res