Blocked Cross Origin Spring Boot And React - java

I am working on a project in react and spring boot, and I got issue with the cross origin from my spring server, I put the crossOrogin annotation on my controller and is not working me I tried many ways (from spring official web) non of them worked to me. Is anyone can help me please with that I really don’t know what to do. Here is my controller , ;
},
And this is my error with react:
error image for react uskg chrome

try this way:
#Configuration
public class CrossConfig implements WebMvcConfigurer {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*") // SpringBoot2.4.0 [allowedOriginPatterns]replace[allowedOrigins]
.allowedMethods("*")
.maxAge(3600)
.allowCredentials(true);
}
}

Related

Access to XMLHttpRequest at 'http://localhost:8080/blog/updatePost/2' from origin 'http://localhost:3000' has been blocked by CORS policy:

Even though I used #CrossOrigin annotation this error still appears. Spring boot app is running on 8080 port and react app is running on 3000 port.
Error:
If further information is needed, please let me know.
I assume you are using spring security.
#CrossOrigin filter might have a lower precedence over spring security filters. Try to configure CORS using spring security.
I resolved my issue with the answer given by #Sanura. Then blockage done by the CORS is avoided.
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/auth/login", "/auth/register","/post/savePost", "/post/**", "/post/getPost/{id}","/post/updatePost/{id}")
.permitAll().anyRequest().authenticated()
.and().exceptionHandling().and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
}
I added the routes to the configure method as above.
The below mentioning code sample also can be used instead of this.
package com.myapp.springboot.configs;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/*").
allowedOrigins("*").
allowedMethods("*").
allowedHeaders("*").
allowCredentials(true);
}
}
Thank you for your support.

Issue regarding JWT token and CORS in Spring and React

I am trying to create a spring boot application that uses a token authentication method. I wanted to go easy so I used this repo https://www.bezkoder.com/spring-boot-login-example-mysql/ as inspiration. No SQL problems. My code is exactly the same as that one there.
When I am doing requests in POSTMAN everything works fine and nothing is wrong.
When I am doing a request in the front end, I get a CORS error that I miss a header or some sort. I fixed that by adding the following class in the project
#Configuration
#EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry
.addMapping("/**")
.allowCredentials(true)
.allowedHeaders("*")
.allowedOrigins("http://localhost:3000");
}
}
At that point, I get the set-cookie header with the correct value, but the cookie is not set. I have also added the withCredentials: true in the header request in AXIOS. Can someone explain to me what is going on and show a solution to this problem using React as frontend?
Many thanks!

Spring Boot CORS settings: CrossOrigin annotation works addCorsMappings doesn't

I have a Spring Boot Rest application where I need to allow CORS requests.
Requests use the common path <host>:<port>/api/... and so far I only have two resources:
package my.controllers;
#RestController
#RequestMapping(path="/", produces="application/json")
public class DataController {
#GetMapping("/")
public ApiResponse<Map<String, Object>> getValues() {
// ...
}
#GetMapping("/sub")
public ApiResponse<String> getValuesSub() {
// ...
}
Here are two example requests from the Javascript client running at http://localhost:3000/:
fetch('http://localhost:2001/api/').then(/* ... */);
fetch('http://localhost:2001/api/sub')).then(/* ... */);
If I add the #CrossOrigin(origins = "*") annotation to the controller, CORS requests work fine; if I replace it implementing WebMvcConfigurer.addCorsMappings() though:
#ComponentScan(basePackages={ "my.controllers" })
#Configuration
public class WebappConfig implements WebMvcConfigurer {
// ...
#Override
public void addCorsMappings(CorsRegistry registry) {
LogManager.getLogger(getClass()).info("CORS settings");
registry.addMapping("/api/**").allowedOrigins("*").maxAge(3600);
}
CORS requests fail, and I get (in Firefox, Chrome shows a similar error message):
CORS header 'Access-Control-Allow-Origin' missing
I see the log entry, so the method is surely invoked.
I've seen other questions mentioning Spring Security or Spring Data (I use none), so here's my dependencies list in case I'm missing something:
spring-boot-starter-web
spring-boot-starter-tomcat
spring-boot-starter-log4j2
spring-boot-configuration-processor
commons-lang3
commons-beanutils
What's the right way to set CORS settings to the whole application, without using the #CrossOrigin annotation on each controller?
UPDATE
I'm initializing a Rest servlet like this:
#Bean
public ServletRegistrationBean<DispatcherServlet> registerDispatcherServlet(DispatcherServlet servlet) {
ServletRegistrationBean<DispatcherServlet> registration = new ServletRegistrationBean<>(servlet);
servlet.setContextConfigLocation("");
registration.addUrlMappings("/api/*");
registration.setLoadOnStartup(1);
return registration;
}
The logs says:
Servlet dispatcherServlet mapped to [/api/*]
Servlet dispatcherServlet mapped to [/]
Servlet dispatcherServlet was not registered (possibly already registered?)
Could it be that the given Cors settings are going to the mentioned unregistered servlet?
I got it working by replacing "/api/**" with "/**" in the call to addMapping() when configuring the CORS registry:
#Override
public void addCorsMappings(CorsRegistry registry) {
LogManager.getLogger(getClass()).info("CORS things!");
registry.addMapping("/**").allowedOrigins("*").maxAge(3600);
}
Though I'm puzzled about why this is the setting that makes it work, and what would I have to do if I need to expose several independent Rest paths, i.e.:
http:/host:port/public-api (from all over the Internet)
http:/host:port/reserved-api (from well known hosts)
http:/host:port/admin-api (same host only)

Spring CORS settings

I'm trying to enable the cross origin header to be able to reach the service from anywhere (only on local env) but I cannot.
#Configuration
#RequiredArgsConstructor
public class CrossOriginConfig implements WebMvcConfigurer {
private final SecurityConfiguration securityConfiguration;
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("*").allowedOrigins(securityConfiguration.getCrossOrginFilter());
}
}
I made a custom index.html with an ajax call and it fails due to the Allow-Cross-Origin header missing and it comes from another origin.
Simple Spring Boot 2.0 controllers are used with #RestController annotation and simple #GetMapping.
What I missed? What should I include and where?
You need to add the below annotation on either on the controller class or the specific method:
#CrossOrigin
By default, its allows all origins, all headers, the HTTP methods specified in the #RequestMapping annotation and a maxAge of 30 minutes is used.
If you want to allow only http://localhost:8080 to send cross-origin requests
#CrossOrigin(origins = "http://localhost:8080")
Replace the host and port accordingly.
Check the below Spring documentation for more information:
https://spring.io/guides/gs/rest-service-cors/
As Georg Wittberger pointed out the problem was with the mapping. I used the * wildcard what is not good for paths.
Instead of this: registry.addMapping("*")
I used this: registry.addMapping("/**") and it's working fine.

Error during WebSocket handshake: Unexpected response code: 403

I have implemented WebSockets with Spring Boot Application and have the below error message when trying to test the ws connection with the chrome extension 'Smart websocket client'.
However, I have no problem when run the Spring Boot Application locally.
WebSocket connection to 'ws://192.168.X.XYZ:8080/test' failed:
Error during WebSocket handshake: Unexpected response code: 403
The only difference which I see is in the Request headers:
In the one it works - Origin:http://192.168.X.XYZ:8080
In the one it does not work - Origin:chrome-extension://omalebghpgejjiaoknljcfmglgbpocdp
What I did in the WebSocketConfig class is below:
#Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myHandler(), "/test").setAllowedOrigins("http://192.168.X.XYZ:8080");
}
and still does not work.
Could you please advise what the reason for that error might be and how to fix it?
Thank you in advance.
You need to configure your "chrome-extension://..." origin as an allowed origin or even "*", otherwise it's rejected by the server.
On update to spring boot 2.4, it also requires:
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
};
}
and #EnableAutoConfiguration on the config class.

Categories