Sunday, September 20, 2020

Enabling cross origin requests for restful web services - spring boot

Enabling cross origin requests for restful web services - spring boot CORS

Cross-origin resource sharing is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served


1.   Add following component class

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

@Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

 @Override
    public void destroy() {

    }

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods","GET,POST,DELETE,PUT,OPTIONS,PATCH");
response.setHeader("Access-Control-Allow-Headers","Authorization,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers");
 response.setHeader("Access-Control-Allow-Credentials", "true");
 response.setHeader("Access-Control-Max-Age", "180");
 filterChain.doFilter(req, res);
}
}


2.    Add the following piece of code inside you WebSecurity Configuration class to                                  enable custom CorsFilter 

@Autowired
CorsFilter myCorsFilter;

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.addFilterBefore(myCorsFilter, SessionManagementFilter.class)
.csrf().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}



Labels: , , , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home