How to fix Cors error Access-Control-Allow-Origin missing - spring-boot

I have a spring boot rest application and I am not using Spring security. My rest service looks like this
#RestController
#CrossOrigin
public class AuthenticationService {
...
#GetMapping(path = "/getUser")
public JSONObject getUser() {
...
}
}
I call the API from a REST application using axios get. Everything works fine locally.
But when the application is deployed on cloud as a docker image, I get the 403 error
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Even when I add a CorsConfiguration file I get the same error.
#Configuration
public class CorsConfiguration {
#Bean
public WebMvcConfigurer corsConfigurer()
{
return new WebMvcConfigurer() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*")
.allowedHeaders("Accept", "Origin", "X-Requested-With,Content-Type", "Authorization", "X-XSRF-Header")
.allowCredentials(true);
}
};
}
}
I have spent a lot of time to find a solution for this but somehow it isn't working.

Declaring a bean works fine for me:
#Configuration
public class WebConfigurer implements ServletContextInitializer, WebMvcConfigurer {
private final Environment env;
private final MyProperties properties;
public WebConfigurer(Environment env, MyProperties properties) {
this.env = env;
this.properties = properties;
}
#Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = properties.getCors();
if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
log.debug("Registering CORS filter");
source.registerCorsConfiguration("/api/**", config);
source.registerCorsConfiguration("/management/**", config);
source.registerCorsConfiguration("/v3/api-docs", config);
}
return new CorsFilter(source);
}
}
Yaml properties:
# CORS is only enabled by default with the "dev" profile
cors:
allowed-origins: '*'
allowed-methods: '*'
allowed-headers: '*'
exposed-headers: 'Authorization,Link,X-Total-Count'
allow-credentials: true
max-age: 1800

fixed by adding spring security

Related

spring cloud gateway with sso

I have an old application with springboot 2.1.3 where zuul proxy is used as API gateway. With Zuul|SSO|Feign is also implemented. Due to recent vulnerabilites, we are migrating to springboot 2.6.8 where we need to migrate zuul to spring cloud gateway along with cors, sso and Feign. I have implemented spring cloud gateway but not able to understand about sso and feign. Below giving some reference with existing code and new as well.
#EnableFeignClients
#EnableDiscoveryClient
#EnableZuulProxy
#EnableOAuth2Sso
#SpringBootApplication(exclude = { MongoAutoConfiguration.class, MongoDataAutoConfiguration.class,
MongoReactiveAutoConfiguration.class, DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
public class SampleApplication {
private Logger logger = LoggerFactory.getLogger(SampleApplication.class);
#Value("${spring.cloud.consul.discovery.instanceId}")
private String instanceId;
#Value("${spring.cloud.consul.host}")
private String host;
#Value("${spring.cloud.consul.port}")
private String port;
public static void main(String[] args) {
new SpringApplicationBuilder(SampleApplication.class).web(WebApplicationType.SERVLET).run(args);
}
#Bean
public RequestInterceptor getUserFeignClientInterceptor() {
return new UserFeignClientInterceptor();
}
#Bean
public FilterRegistrationBean<CorsFilter> simpleCorsFilter() {
logger.debug("simpleCorsFilter called");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
#PreDestroy
public void shutdown() {
logger.info("service {} is shutting down", instanceId);
RestTemplate restTemplate = new RestTemplate();
String url = String.format("http://%s:%d/agent/service/deregister/%s", host, port, instanceId);
try {
restTemplate.put(url, null);
} catch (Exception e) {
logger.error("{}", e);
}
}
}
SpringSecurity Conffiguration
#Configuration
#Order(Ordered.HIGHEST_PRECEDENCE)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
public void configure(WebSecurity web) throws Exception {
//web.ignoring().antMatchers(HttpMethod.OPTIONS).antMatchers("/actuator/**");
web.ignoring().antMatchers(HttpMethod.OPTIONS).antMatchers("/**");
}
#Override
public void configure(HttpSecurity http) throws Exception {
http.cors().and()
.requestMatcher(new RequestHeaderRequestMatcher("Authorization")).authorizeRequests().antMatchers("/**")
.authenticated().and().csrf().disable();
}
FiegnInterceptor
public class UserFeignClientInterceptor implements RequestInterceptor {
private static final String AUTHORIZATION_HEADER = "Authorization";
private static final String BEARER_TOKEN_TYPE = "Bearer";
#Override
public void apply(RequestTemplate template) {
SecurityContext securityContext = SecurityContextHolder.getContext();
Authentication authentication = securityContext.getAuthentication();
if (authentication != null && authentication.getDetails() instanceof OAuth2AuthenticationDetails) {
OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
template.header(AUTHORIZATION_HEADER, String.format("%s %s", BEARER_TOKEN_TYPE, details.getTokenValue()));
}
}
}
SpringCloudGateway - New imeplementation where defined all the routes and global cors but not sure how to use sso and openfeign.
spring:
application:
name: SampleApplicationNew
cloud:
gateway:
discovery:
locator:
enabled: true
routes:
- id: Microservice1
uri: lb://Microservice1
predicates:
- Path=/microservice1/**/
globalcors:
corsConfigurations:
'[/**]':
allowedOrigins: "*"
allowedHeaders:
- "*"
allowedMethods:
- GET
- POST

XMLHttpRequest at xxx from origin xxx has been blocked by CORS: No 'Access-Control-Allow-Origin' header

hi I am working on spring boot, angular 8, and mongodb. I am facing the error
Access to XMLHttpRequest at 'http://localhost:8080/employee/activeemployeesummary' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
when i test same code on postman it work perfectly fine, however it don't work angular, and because chrome using the CORS policy.
My code:
package com.sani.springbootrestfulapi;
public class SpringBootMongoApplication extends SpringBootServletInitializer {
public static void main(String args[]) {
SpringApplication.run(SpringBootMongoApplication.class, args);
}
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH")
.allowedHeaders("Origin, X-Requested-With, Content-Type, Accept")
.allowedOrigins("http://localhost:4200");
}
};
}
}
below: employee controller code
package com.sani.springbootrestfulapi.controller;
#RestController
#RequestMapping("employee")
public class EmployeeController {
#Autowired
private EmployeeService empService;
#Autowired
private OrganizationService organizationService;
#PostMapping("/save")
public ResponseEntity<EmployeeEntity> save(#RequestBody EmployeeEntity emp) {
if (empService.findByrNumber(emp.getrNumber()))
return new ResponseEntity<EmployeeEntity>(HttpStatus.FOUND);
else {
organizationService.joinOrganization(emp);
return new ResponseEntity<EmployeeEntity>(HttpStatus.OK);
}
}
#PutMapping("/update") /* here we need to pass id, the spring will consider as update */
public ResponseEntity<EmployeeEntity> update(#RequestBody EmployeeEntity emp) {
EmployeeEntity employee = empService.getOne(emp.getId());
if (employee != null) {
organizationService.joinOrganization(emp);
return new ResponseEntity<EmployeeEntity>(HttpStatus.OK);
} else
return new ResponseEntity<EmployeeEntity>(HttpStatus.NOT_FOUND);
}
#GetMapping("/activeemployeesummary")
public List<EmployeeEntity> getActiveEmployeeSummary() {
List<EmployeeEntity> employee = new ArrayList<>();
empService.getActiveEmployeeSummary().forEach(employee::add);
return employee;
}
#GetMapping("/inactiveemployeesummary")
public List<EmployeeEntity> getInactiveEmplo`enter code here`yeeSummary() {
List<EmployeeEntity> employee = new ArrayList<>();
empService.getInactiveEmployeeSummary().forEach(employee:`enter code here`:add);
return employee;
}
}
Add this #Bean in your #Configuration or your main class.
#Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(
Arrays.asList("GET","POST","HEAD","DELETE","PUT","OPTIONS"));
configuration.setMaxAge(1l);
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(Arrays.asList("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
I think you just missed that header =>
Access-Control-Allow-Origin: *

Enabling CORS in Spring Secondary Servlet

I am registering a secondary servlet using Spring boot's ServletRegistrationBean
#Configuration
public class CxfServletRegister {
#Bean
public ServletRegistrationBean getODataServletRegistrationBean() {
ServletRegistrationBean odataServletRegistrationBean = new ServletRegistrationBean(new CXFNonSpringJaxrsServlet(), "/odata.svc/*");
Map<String, String> initParameters = new HashMap<String, String>();
initParameters.put("javax.ws.rs.Application", "org.apache.olingo.odata2.core.rest.app.ODataApplication");
initParameters.put("org.apache.olingo.odata2.service.factory", "com.cce.utils.JPAServiceFactory");
odataServletRegistrationBean.setInitParameters(initParameters);
return odataServletRegistrationBean;
}
}
I am building an OData application using Apache Olingo. I want CORS to be enabled for my service.
How do I enable CORS for this servlet?
PS I have tried the WebConfigurer bean from the Spring: Getting Started guides
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/greeting-javaconfig").allowedOrigins("*");
}
};
}
This doesn't work, probably because this is configuring spring web's default dispatcher servlet and not the additional servlet configured using the ServletRegistrationBean
I found a likely way to do it here:
https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
#Configuration
public class MyConfiguration {
#Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://domain1.com");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}

Enable CORS On Spring accessing MongoDB data

I'm trying to develop a RestFul Web Service with Spring, that fetches data from a mongoDB collection and serves it to a client. To build the service i followed this guide on spring.io. Everything went well, i can access data from mongoDB and search it for the data structure name.
The troubles began when i tried to manage requests from my client, i receive classical error of same-domain-policy violation.
No 'Access-Control-Allow-Origin' header is present on the requested
resource.
The project is EXTREMELY simple, is composed of those 3 classes:
Frames.java
#Id
private String Id;
private String frameName;
private ArrayList<String> frameElements;
public String getId() {
return Id;
}
public String getFrameName() {
return frameName;
}
public ArrayList<String> getFrameElements() {
return frameElements;
}
FrameRestFulServiceApplication.java
#SpringBootApplication
public class FrameRestFulServiceApplication {
public static void main(String[] args) {
SpringApplication.run(FrameRestFulServiceApplication.class, args);
}
}
FramesRepository.java
#RepositoryRestResource(collectionResourceRel = "frames", path = "frames")
public interface FramesRepository extends MongoRepository<Frames, String>{
List<Frames> findByFrameNameLike(#Param("frameName") String frameName);
List<Frames> findByFrameName(#Param("frameName") String frameName);
}
I tried different methods found in the documentation See here but without results...
A similar question is Spring Data Rest and Cors
The answer is that if you are using Spring Boot (which supports Filter beans), it could be something like:
#Configuration
public class RestConfiguration {
#Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true); // you USUALLY want this
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
have you tried to add a class like this?
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
it worked for me

Enabling Cross Origin Resource Sharing for Spring Data Rest

I'm developing Spring (non-Boot) application with Spring 4.2.1 version. I've enabled CORS for Spring MVC in web configuration file.
#Configuration
#EnableWebMvc
#ComponentScan({"com.hello.web", "com.hello.rest"})
#Import(RestMvcConfig.class)
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
And it was working correct. But now i started to use String Data Rest 2.4 and integrated it with Spring MVC. How to enable Cross Origin Resources Sharing for Spring Data Rest controllers? I've tried to fix it with filter bean Spring Data Rest and Cors
#Configuration
public class RestMvcConfig extends RepositoryRestMvcConfiguration {
#Override
public RepositoryRestConfiguration config() {
RepositoryRestConfiguration config = super.config();
config.setBasePath("/api");
config.setDefaultMediaType(new MediaType("application", "json", Charset.forName("utf-8")));
return config;
}
#Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true); // you USUALLY want this
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
But CORS is still not allowed.
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403.
How to enable CORS for Spring Data Rest?

Resources