CORS从s3发出调用ec2

时间:2018-09-17 18:59:17

标签: amazon-s3 amazon-ec2 cors

从s3调用ec2时出现以下核心问题。我正在尝试从s3到ec2进行通话。

OPTIONS http://ec2-18-222-201-68.us-east-2.compute.amazonaws.com:8080/register 403 ()

registration.html:1 Failed to load http://ec2-18-222-201-68.us-east-2.compute.amazonaws.com:8080/register: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://htmlcode.s3-website.us-east-2.amazonaws.com' is therefore not allowed access.

下面是我在s3存储桶中设置的CORS

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <AllowedMethod>GET</AllowedMethod>
    <MaxAgeSeconds>10000</MaxAgeSeconds>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

我还在ec2 springboot jar文件中设置了带有必要标头的CORS过滤器。我该如何解决这个问题。

下面是我的核心过滤器

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter extends GenericFilterBean implements Filter {

    public CorsFilter() {
        super();
    }   

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, content-type");
        response.setHeader("Access-Control-Expose-Headers", "authorization");

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }

}

1 个答案:

答案 0 :(得分:1)

您的响应说"Access-Control-Allow-Origin"不存在,因此您需要确保您的ec2侧面jar发送此标头作为对预检请求的响应,并且值应与您的请求来源(ec2)域名匹配。

在我的情况下,我使用的是Spring RestController,下面的内容用于允许所有域的类级别注释:

@CrossOrigin("*")