Skip to content

Instantly share code, notes, and snippets.

@brunocribeiro
Last active May 12, 2019 06:56
Show Gist options
  • Save brunocribeiro/c411b2c331379ca9604f to your computer and use it in GitHub Desktop.
Save brunocribeiro/c411b2c331379ca9604f to your computer and use it in GitHub Desktop.
Set of configuratons to enable CORS in AngularJS with Java Environments
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:cors>
<!-- allowed-origins: '*' by default, you can use just a few -->
<mvc:mapping path="/**" max-age="3600"
allowed-headers="origin, content-type, accept, authorization"
allowed-methods="GET, POST, PUT" />
</mvc:cors>
</beans>
// enable cors for Angular JS, can be a module
var app = angular.module('app', ['appApiService']);
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
package com.brunocesar.config;
import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
@Provider
public class CORSFilter implements ContainerResponseFilter {
@Override
public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext cres) throws IOException {
cres.getHeaders().add("Access-Control-Allow-Origin", "*"); // you can use just a few
cres.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
cres.getHeaders().add("Access-Control-Allow-Credentials", "true");
cres.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT");
cres.getHeaders().add("Access-Control-Max-Age", "3600");
}
}
package com.brunocesar.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* Spring Java Config
*/
@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(final CorsRegistry registry) {
registry.addMapping("/**");
//.allowedOrigins("*") '*' by default, you can use just a few
.allowedMethods("GET", "POST", "PUT")
.allowedHeaders("origin", "content-type", "accept", "authorization")
.maxAge(3600);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment