How Can I Disable ssl certificate Spring RestTemplate? - spring

In my Spring boot project I am trying to intercept the following POST call "https: // localhost: 8080" but I get the following error:
java.lang.IllegalArgumentException: Invalid character found in method name
I already know that to solve the problem it would be enough to change from https to http. But I don't want this.
I want my code to be able to automatically handle this situation.
In any case if I try to reach
This is the configuration of my RestTemplate in the App class:
How could I go about solving the problem ??
This is the configuration of my RestTemplate in the App class:
#EnableFeignClients
#ServletComponentScan
#Import(EmbeddedTomcatConfiguration.class)
// uncomment to enable auditor
//#EnableJpaAuditing(auditorAwareRef = "auditorAware")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
#Bean
public RestTemplate restTemplate() {
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(
HttpClientBuilder.create().build());
RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
return restTemplate;
}
#Autowired(required = true)
public void configureJackson(ObjectMapper jackson2ObjectMapper) {
// jackson2ObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
jackson2ObjectMapper.registerModule(new JavaTimeModule());
jackson2ObjectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
#Bean
public FilterRegistrationBean<CorsFilter> filterRegistrationBean() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = buildCorsConfiguration();
source.registerCorsConfiguration("/**", config);
final FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
private CorsConfiguration buildCorsConfiguration() {
final CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
config.addExposedHeader(HttpHeaders.LOCATION);
return config;
}
}
How could I go about solving the problem ??

Related

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

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

Spring RestTemplate and HttpClient connection pooling limit

I'm using RestTemplate on my jsf web server, and with these configuration I often reach limit of connection to routes so soon (exp:/ap-domain/get-all).
How can I release connection to avoid limit?
This is my config class:
#Configuration
public class RestTemplateConfig {
#Bean
public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager() {
PoolingHttpClientConnectionManager result = new PoolingHttpClientConnectionManager();
result.setMaxTotal(100);
result.setDefaultMaxPerRoute(20);
return result;
}
#Bean
public CloseableHttpClient httpClient() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
CloseableHttpClient result = HttpClientBuilder.create()
.setConnectionManager(poolingHttpClientConnectionManager())
.setDefaultRequestConfig(requestConfig())
.setSSLSocketFactory(csf)
.build();
return result;
}
#Bean
public RestTemplate restTemplate() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient());
RestTemplate restTemplate = new RestTemplate(requestFactory);
restTemplate.setErrorHandler(new RestResponseErrorHandler());
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
if (interceptors.isEmpty()) {
interceptors = new ArrayList<>();
}
interceptors.add(new RestTemplateHeaderInterceptor());
restTemplate.setInterceptors(interceptors);
return restTemplate;
}
}
My RestUtil to call api:
#Component
public class RestUtil {
private static RestTemplate restTemplate;
#Autowired
public RestUtil(RestTemplate restTemplate) {
RestUtil.restTemplate = restTemplate;
}
public static <T> MessagesResponse<T> exchange(String url, HttpMethod method, Object requestObject, String token, ParameterizedTypeReference<MessagesResponse<T>> type) {
...
}
}

Spring MVC CORS not working for error controllers

I have my Spring MVC application configured to use CORS as such:
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
This works fine for successful requests however when an exception is thrown and is picked up by my error handler, CORS headers are not added.
#ControllerAdvice
public class ApiErrorHandler {
#ExceptionHandler(value = HttpClientErrorException.class)
public ResponseEntity badRequest(Exception ex)
{
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ErrorBodyWrapper.wrapErrorInJson(ex.getMessage()));
}
}
Is there a reason CORS does not work for error handlers?
Thanks
I think by default the only method added to the mapping is GET,
In your "addCorsMappings" try to specify the methods you want to add the header to
registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD");
Using Spring CorsFilter can resolve this problem.
#Bean
public FilterRegistrationBean<CorsFilter> corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
bean.setOrder(0);
return bean;
}

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;
}
}

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