Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cors enabled in Spring Boot with Angular, still cors errors

I have cors enabled for all origins and headers but I still get an cors error when I call a get method from my angular app to spring boot.

Cors error from console:

Access to XMLHttpRequest at 'http://localhost:8080/api/users/[email protected]' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

My controller (I call the getbyemail):

@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
@RequestMapping(value = "/api/users", produces = MediaType.APPLICATION_JSON_VALUE)
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(final UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public List<UserDTO> getAllUsers() {
        return userService.findAll();
    }

    @GetMapping("/{id}")
    public UserDTO getUser(@PathVariable final Long id) {
        return userService.get(id);
    }

    @CrossOrigin(origins = "*", allowedHeaders = "*")
    @GetMapping("/{email}")
    public UserDTO getUserByMail(@PathVariable String email) {
        return userService.getByEmail(email);
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public Long createUser(@RequestBody @Valid final UserDTO userDTO) {
        return userService.create(userDTO);
    }

    @PutMapping("/{id}")
    public void updateUser(@PathVariable final Long id, @RequestBody @Valid final UserDTO userDTO) {
        userService.update(id, userDTO);
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteUser(@PathVariable final Long id) {
        userService.delete(id);
    }

}

Where I call the get from my angular app:

onSubmit(): void {
    this.submitted = true;
    this.wrongInput = false;
    this.loginService.getLogin<User>(this.loginForm.value.email).subscribe((response) => {
      this.tempUser = response;
      console.log(this.tempUser);
      if (this.loginForm.value.email === this.tempUser.email && this.loginForm.value.password === this.tempUser.password) {
        this.localStorageService.save(this.tempUser);
        this.router.navigate(['/home']);
        console.log(true);
      }
      else {
        this.wrongInput = true;
      }
    });
  }

I also tried to add an DevCorsConfiguration:

package com.team13.triviaquiz.triviaquizserver.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@Profile("development")
public class DevCorsConfiguration implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**").allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS");
    }
}

And added the profile in my application.properties:

application.properties
spring.profiles.active=development
#enabling h2 console
spring.h2.console.enabled=true
#fixed URL for H2 (necessary from Spring 2.3.0)
spring.datasource.url=jdbc:h2:mem:triviaquizserver
#turn statistics on
spring.jpa.properties.hibernate.generate_statistics = true
logging.level.org.hibernate.stat=debug
#show all queries
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.type=trace

But still no luck...

like image 646
Ronny Giezen Avatar asked Nov 18 '20 11:11

Ronny Giezen


People also ask

How do I fix CORS error in spring boot?

Enable CORS in Controller Method We need to set the origins for RESTful web service by using @CrossOrigin annotation for the controller method. This @CrossOrigin annotation supports specific REST API, and not for the entire application.

Is CORS enabled by default in spring boot?

Controller Method CORS ConfigurationBy default, its allows all origins, all headers, and the HTTP methods specified in the @RequestMapping annotation. Also, a maxAge of 30 minutes is used. You can customize this behavior by specifying the value of one of the following annotation attributes: origins.


1 Answers

This could be due to a change in Spring libraries, thus affecting Spring Boot 2.4.0. Look here https://github.com/spring-projects/spring-framework/issues/26111 and to its related ticket https://github.com/spring-projects/spring-framework/pull/26108

EDIT Here the original message from the 1st link:

#25016 introduced the ability to configure allowedOriginPatterns in addition to just allowedOrigins. It lets you define more flexible patterns while the latter is literally the value to return in the Access-Control-Allow-Origin header and for that "*" is not allowed in combination with allowCredentials=true. The change introduced equivalent allowedOriginPatterns methods in the WebMvc and the WebFlux config, but not in the SockJS config and the AbstractSocketJsService.

I'll add those for 5.3.2. You'll then need to switch to allowedOriginPatterns instead of allowedOrigins but that gives you an option to define more precisely the allowed domain patterns. In the mean time, you might be able to work around by listing specific domains if that's feasible.

like image 58
mau Avatar answered Nov 15 '22 22:11

mau