user3310115
user3310115

Reputation: 1460

CORS Issue calling ec2 from s3

I'm getting the below core issue while calling ec2 from s3. I am trying to make a rest call from s3 to 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.

Below is my set-up of CORS in the s3 bucket

<?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>

I have also setup CORS Filter in my ec2 springboot jar file with the necessary headers. How can I resolve this issue.

Below is my core filter

@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() {

    }

}

Upvotes: 0

Views: 359

Answers (1)

Sharman25
Sharman25

Reputation: 69

your response says "Access-Control-Allow-Origin" is not present, so you need to make sure your ec2 side jar sends back this header as response to preflight requests and the values should match your requested-from (ec2) domain name.

In my case, I am using spring RestController, and below works on a class level annotation for allowing all domains:

@CrossOrigin("*")

Upvotes: 1

Related Questions