I am using react as FE and Spring for the BE services. I have a controller class with several different methods (mainly POST and GET) and have annotated it with @CrossOrigin. When authenticating the user, it works just fine and the method is available, however all other methods return CORS error. Errors I receive is:
Access to fetch at 'http://localhost:9002/users/simpleUser/1,function%20()%20%7B%20[native%20code]%20%7D' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
UserService.jsx:38
GET http://localhost:9002/users/simpleUser/1,function%20()%20%7B%20[native%20code]%20%7D net::ERR_FAILED
My controller class is as follows:
@CrossOrigin
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserServiceImpl userService;
@Autowired
private JWTUtil jwtUtil;
@Autowired
private AuthenticationManager authenticationManager;
@GetMapping("/simpleUser/{id}")
public AppUser getUser(@PathVariable("id") Long userId) {
return this.userService.getSimpleUser(userId);
}
@GetMapping("/all")
public List<AppUser> getAllUsers() {
return this.userService.getAllUsers();
}
@PostMapping("/authenticate")
public JwtResponse authenticate(@RequestBody JwtRequest jwtRequest) throws Exception {
--some logic here--
}
Authenticate method which is POST works, however all other ones return the error
I have tried annotating the methods with
@CrossOrigin(value="*")
and the class with @CrossOrigin(maxAge = 3600, methods = {RequestMethod.POST, RequestMethod.GET})
however none of those works.
I have also tried adding cors in the security config
@Override protected void configure(HttpSecurity http) throws Exception { http.cors().and()...
but this doesn't work either. Anyone that can help?
react code for fetching is:
async getUser(userId, token) {
return await fetch(`${USER_ENDPOINTS.GET_USER}/${userId}`, {
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
},
}).then(async (response) => {
const userGot = await response.json();
console.log("user:" + userGot);
return userGot;
});
}
Edit: fixed it, the problem was adding cors to the security configuration AFTER authenticated antMatchers
http.csrf()
.disable()
.authorizeRequests()
.antMatchers(""/users/save")
.permitAll()
.anyRequest()
.authenticated()
.and()
.cors().and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);