【发布时间】:2020-11-21 10:35:45
【问题描述】:
我正在尝试使用 angular 和 spring 做简单的 CRUD。我在我的 Spring Boot 应用程序中实现了 JWT 身份验证。之后,每当我执行插入操作时,它都可以正常工作,但是每当我尝试编辑和删除它时,都会给出“origin 'http://localhost:4200' has been blocked by CORS policy'错误。为什么我收到此错误我在安全配置中添加了“CorsFilter”bean,但它仍然给我同样的错误。 在添加 JWT 身份验证之前,所有 CRUD 操作都运行良好。
请告诉我为什么会出现此错误。
SecurityConfig.java
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.
cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues())
.and().csrf().disable()
.authorizeRequests()
.antMatchers("/**").permitAll()
.antMatchers("/").hasRole("ADMIN")
.antMatchers("/*").hasRole("USER")
.and()
.exceptionHandling()
.accessDeniedPage("/access-denied")
.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(authenticationManager(), customUserDetailService));
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
configuration.setAllowCredentials(true);
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type", "xsrfheadername","xsrfcookiename"
,"X-Requested-With","XSRF-TOKEN","Accept", "x-xsrf-token","withcredentials","x-csrftoken"));
configuration.setExposedHeaders(Arrays.asList("custom-header1", "custom-header2"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
控制器
@RestController
public class StudentController {
@CrossOrigin(origins = "http://localhost:4200")
@PostMapping(value = "/info")
public List<Info> addproduct(@RequestBody Info info) {
signupDAO.add(info);
List<Info> addinfo = signupDAO.getAllInfo();
return addinfo;
}
@RequestMapping(value = "/infoDelete/{id}")
public void deleteStudent(@PathVariable int id) {
System.out.println("this is deleteid");
signupDAO.delete(id);
}
@PutMapping("/infos/{id}")
public String updateStudent(@RequestBody Info info, @PathVariable int id) {
info.setId(id);
signupDAO.update(info);
return "info";
}
}
LoginService.ts
webInfo(data: Student): Observable<any> {
const url = '/info';
return this.httpClient.post(this.serverUrl + url, data);
}
editPlan(data: Student, id: any): Observable<any> {
const url = `/infos/${id}`;
return this.httpClient.put(this.serverUrl + url, data);
}
deletePlan(id: any): Observable<any> {
const url = `/infoDelete/${id}`;
return this.httpClient.delete(this.serverUrl + url);
}
【问题讨论】:
-
我尝试了很多解决方案,但没有任何效果。
-
对于本地测试,您可以在不检查 cors 的情况下启动 chrome,例如在 Mac 上使用: open -n -a /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --args --user-data-dir="/tmp/chrome_dev_test" --disable-web-security
-
好的,我不太确定,但您的 cors 配置要么损坏,要么有问题。因为如果 1 个操作运行良好,则表明配置损坏。
-
我需要在这些请求中添加 jwt 令牌吗?
标签: angular spring-boot cors