For a Proof of concept I am trying to load a jsp from one spring boot app on a section of a page on another.
I am using JQuery to make a $.ajax() request but from what I can see is that the request isnt even getting to spring filters or controller. The controller response normally when sending from its own browser window.
Error: Failed to load http://localhost:8082/settings2: Redirect from 'http://localhost:8082/settings2' to 'http://localhost:8082/settings2/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
2 Applications: settings & settings2. Settings one is trying make an AJAX request to a controller on settings2
settings app page (trying to talk to settings2 app)
<script>
$.ajax({url:'http://localhost:8082/settings2',
type:"POST");
}});
//No success method because chrome console already showing error
</script>
</body>
Settings2 configuration app (WebMvcConfigurerAdapter is flagged as depreciated) @Configuration public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/").allowedOrigins("http://localhost:8080", "*")
.allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH", "OPTIONS").allowedHeaders("*")
.exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Methods",
"Access-Control-Allow-Headers", "Access-Control-Max-Age", "Access-Control-Request-Headers",
"Access-Control-Request-Method");
}
}
Settings2 websecurity config
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
configuration.setExposedHeaders(Arrays.asList("Access-Control-Allow-Origin", "Access-Control-Allow-Methods",
"Access-Control-Allow-Headers", "Access-Control-Max-Age", "Access-Control-Request-Headers",
"Access-Control-Request-Method"));
// setAllowCredentials(true) is important, otherwise:
// The value of the 'Access-Control-Allow-Origin' header in the response must
// not be the wildcard '*' when the request's credentials mode is 'include'.
configuration.setAllowCredentials(true);
// setAllowedHeaders is important! Without it, OPTIONS preflight request
// will fail with 403 Invalid CORS request
configuration.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/", configuration);
return source;
}
}
settings2 app Cors Filter
public class WebSecurityCorsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "*");
res.setHeader("Access-Control-Max-Age", "3600");
res.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(request, res);
}
@Override
public void destroy() {
}
}
Settings2 controller @CrossOrigin @RestController public class SettingsController {
@CrossOrigin
@RequestMapping(value = "/", method = { RequestMethod.POST })
public String getPagePost(HttpServletResponse response) {
return "home";
}
@RequestMapping(value = "/", method = RequestMethod.OPTIONS)
public ResponseEntity handle() {
return new ResponseEntity(HttpStatus.OK);
}
}
Settings2 pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ddavey</groupId>
<artifactId>settings</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>settings2</name>
<description>Development Team Register Application</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Settings2 app startup logs (Nothing further logged even when the request is sent):
. ____ _ __ _ _ /\ / ' __ _ ()_ __ __ _ \ \ \ \ ( ( )_ | '_ | '| | ' / ` | \ \ \ \ \/ )| |)| | | | | || (| | ) ) ) ) ' |____| .|| ||| |__, | / / / / =========|_|==============|___/=///_/ :: Spring Boot :: (v2.0.0.RELEASE)
2018-03-15 13:04:07,585 2029 [restartedMain] DEBUG o.s.s.c.a.a.c.AuthenticationConfiguration$EnableGlobalAuthenticationAutowiredConfigurer - Eagerly initializing {webSecurityConfig=com.ddavey.settings.WebSecurityConfig$$EnhancerBySpringCGLIB$$5891dd83@30260b10} 2018-03-15 13:04:07,724 2168 [restartedMain] INFO o.s.s.w.DefaultSecurityFilterChain - Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher@1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@52e26e68, org.springframework.security.web.context.SecurityContextPersistenceFilter@624ab72f, org.springframework.security.web.header.HeaderWriterFilter@618df83a, org.springframework.web.filter.CorsFilter@1f0c50a, org.springframework.security.web.csrf.CsrfFilter@174cc9cb, org.springframework.security.web.authentication.logout.LogoutFilter@4fddc7f, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@23710a6c, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@231f9098, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@72fafc4, org.springframework.security.web.session.SessionManagementFilter@17b054e5, org.springframework.security.web.access.ExceptionTranslationFilter@57cd8b95]