在Spring Boot中启用了Cors,但仍存在Cors错误



我为所有原点和标头启用了cors,但当我从我的angular应用程序调用get方法以进行春季启动时,仍然会出现cors错误。

来自控制台的Cors错误:

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

我的controller(我叫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);
}
}

我从我的angular应用程序调用get的地方:

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

我还尝试添加一个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");
}
}

并在我的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

但仍然没有运气。。。

这可能是由于Spring库的更改,从而影响了Spring Boot 2.4.0。看这里https://github.com/spring-projects/spring-framework/issues/26111及其相关票据https://github.com/spring-projects/spring-framework/pull/26108

编辑这里是来自第一个链接的原始消息:

#25016引入了除了配置allowedOrigins之外还配置allowed OriginPatterns的功能。它可以让您定义更灵活的而后者实际上是要在Access Control Allow Origin报头*"不允许在中与allowCredentials的组合=true。引入的更改WebMvc和WebFlux中的等效allowedOriginPatterns方法config,但不在SockJS配置和AbstractSocketJsService中。

我将为5.3.2添加这些内容。然后您需要切换到allowedOriginPatterns而不是allowedOrigins,但这会给你一个选项,以更精确地定义允许的域模式。在同时,您可以通过列出特定的域(如果可行的话)。

答案中已经明确提到了这个问题背后的原因,简单地说,CorsRegistry#allowCredentials(true)不能与默认值CorsRegistry#allowedOrigins()一起使用(默认情况下,如果您没有设置此属性,则允许所有来源,除非设置了任何CorsRegistry#allowedOriginPatterns())

  • 用最典型的Spring boot corsMappings来解释这个问题:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*").allowCredentials(true);
}
};
}

在上面的示例中,allowCredentials设置为true,同时allowedOrigins未配置,这意味着默认情况下允许所有原点(allowedOrigins的值将为*)。

  • 要解决此问题,必须显式设置allowedOriginsallowedOriginPatterns。在下面的代码片段中,使用了allowedOriginPatterns,并且该值设置为->CCD_ 16。此通配符模式匹配domain.com中的任何主机,以及类似https:micservice.division.domain.com
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*").allowedOriginPatterns("https://*.domain.com");
}
};
}

完整的代码片段链接

更改corsConfiguration.setAllowedOrigins("*")corsConfiguration.setAllowedOriginPatterns("*")帮了我一把!

所以基本上setAllowedOriginssetAllowedOriginPatterns

在控制器上尝试以下操作

@CrossOrigin(origins = "*", allowCredentials = "true", allowedHeaders = "*", exposedHeaders = "If-Match")

cors错误来自于处理我的两个get方法的不明确处理程序错误。我的controller中有两个get方法,一个取integer,另一个取String。所以它真的无法解析字符串或int(我想)。我已经将get方法的bot路径更改为:

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

这也修复了@CrossOrigin(origins = "*", allowedHeaders = "*")的cors错误在CCD_ 25中。

当我得到错误时,我的场景是:

我在Spring Boot Server应用程序中添加了Spring Boot安全依赖项。

与您的跟踪类似,我添加了CrossOrigin()Annotation来解决这个问题。但这个问题并没有得到解决。

我通过在请求的头选项中添加基本身份验证来解决这个问题。

请参阅帖子,了解如何在标题中添加基本身份验证:

Angular 6 HTTP获取带有HTTP基本身份验证的请求

import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type':  'application/json',
'Authorization': 'Basic ' + btoa('username:password')
})
};

将用户名和密码替换为您的用户名和密码。默认情况下,Spring引导中的用户名为"user",密码将在启动Spring引导应用程序的控制台上生成。

注意:您还必须将CrossOrigin注释添加到您的RequestMapping中。

由于您使用的是基本身份验证,您应该添加WebSecurityConfiguration以允许安全配置,如下所示:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
http.cors();
}
}

参考文献:

  • https://www.baeldung.com/spring-security-cors-preflight
  • https://www.baeldung.com/spring-security-basic-authentication

希望解决方案对您有所帮助。

谢谢昌都

您应该创建一个名为";,代码是以下

package com.api.juego.config;
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 WebMvcConfig implements WebMvcConfigurer {
private final long MAX_AGE_SECS = 3600;
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(false)
.maxAge(MAX_AGE_SECS);
}
}

出于安全原因,允许的方法有GET、POST、PUT、PATCH、DELETE和OPTIONS。

最近我遇到了同样的问题,并尝试了所有可能的方法,但都没有成功。我使用的是spring2.6.7,我添加了下面的代码来解决这个问题。

在Spring引导主类中,您可以添加以下代码

@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowedMethods("*");
}
};
}

你可以看到我添加了addMapping("/**").allowedOrigins("*").allowedMethods("*");

快乐编码!!

相关内容

最新更新