Angular2/Spring Boot Allow Cross Origin on Put

Angular2/Spring Boot Allow Cross Origin on PUT

Create CORSFilter.java file in your project.

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

/**
* CORS filter for http-request and response
*/
public CORSFilter() {
}

/**
* Do Filter on every http-request.
*/
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "access_token, authorization, content-type");

if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}

/**
* Destroy method
*/
@Override
public void destroy() {
}

/**
* Initialize CORS filter
*/
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}

You can refer this post Angular 2 Spring Boot Login CORS Problems

Angular 2 Spring Boot Login CORS Problems

First thing you need to understand Cors configuration is added in the backend. You do not need to send cors header with each request from Angular2 App. Understanding that, this problem is easily fixed by adding global CORS configuration in your spring security configuration class.

First you need to create a filter bean :

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

public MyCorsFilter () {
super();
}

@Override
public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {
final HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");

// without this header jquery.ajax calls returns 401 even after successful login and SSESSIONID being succesfully stored.
response.setHeader("Access-Control-Allow-Credentials", "true");

response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Authorization, Origin, Content-Type, Version");
response.setHeader("Access-Control-Expose-Headers", "X-Requested-With, Authorization, Origin, Content-Type");

final HttpServletRequest request = (HttpServletRequest) req;
if (!request.getMethod().equals("OPTIONS")) {
chain.doFilter(req, res);
} else {
// do not continue with filter chain for options requests
}
}

@Override
public void destroy() {

}

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

STEP 2: In your spring security configuration class add :

@Autowired
private MyCorsFilter myCorsFilter;

//CORS
http.addFilterBefore(myCorsFilter, ChannelProcessingFilter.class);

EDIT :
This configuration assumes you have angular2 app running at localhost:3000

No 'Access-Control-Allow-Origin' in angular with Spring-boot / Http call angular 2

What I have done in angular application was correct and had to correct
my spring boot application only.

The only change I made is creating configuration file called WebSecurityConfig.

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors();
}

@Bean
CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new
UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
}

How to enable CORS between Spring and Angular 2 on localhost

I'm not familiar with spring or java, but I think I understand the problem.

I assume that your logging filter does not work because spring framework short circuit that request before your filter is being executed.

The issue here is probably somewhere in config, but I believe that the approach to the given problem is not right in general.

CORS is created for some purposes, and by allowing requests from browser from all other origins you actually creating some potential security issues.

Ideally, if both: server and client are your apps, from the client side you should make requests only to the same origin which the client app is hosted on. So in your case locally it should make requests to localhost:8081, you can do that by omitting host base address on client side when making requests.

To have it working, for development environment the best option is to set up proxy for angular (to proxy requests from localhost:8081 to localhost:8080), detailed setup info is here.

For production environment you need to host backend-server/client apps on the same origin. You can do that by having some proxy server in front of your backend-server/client web servers, or by hosting client app (angular static output files) directly on your backend-server.

Another option, is to do what you have tried to do, but do not allow requests from all origins (not .permitAll()), instead - list specific allowed origins (like localhost:8081).
But it's not that clean and also you will need to have different origins specified for development environment and for production.



Related Topics



Leave a reply



Submit