CORS with spring boot

CORS (Cross Origin Resource Sharing) allows to make cross domain ajax requests for allowed domain. To setup CORS in spring add the following filter

@Component
public class CORSFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        chain.doFilter(req, res);
    }
    @Override
    public void destroy() {
    }

The ‘Access-Control-Allow-Origin’ parameter controls which domains will be allowed to make cross domain requests and ‘Access-Control-Allow-Methods’ defines the methods that will be allowed


Metadata

116 words

First published on 2018-05-09

Generated on 13 Dec 2024 at 12:12 AM

Index

Mobile optimized version. Desktop version.