spring-boot - 从源“http://localhost:4200”访问“http://localhost:8080/api/auth/userdetails”的 XMLHttpRequest 已被 CORS 策略阻止
问题描述
我已经创建了一个 REST 服务来进行身份验证并且它是成功的。
我创建了另一个服务并通过传递令牌来调用该服务。
它在邮递员中运行良好。
我正在尝试从 Angular 调用它。
登录表单工作正常。
loginURL: string = 'localhost:8080/authenticate';
this.http.post(this.loginURL, {
username: 'headoffice',
password: 'guest'
}).subscribe((successResp) => {
resolve(successResp);
},
(errorResp) => {
resolve(errorResp);
}
);
但是当我调用 localhost:8080/api/auth/userdetails
userDetailsURL: string = 'localhost:8080/api/auth/userdetails';
token: string = '.....';
this.http.post(this.userDetailsURL, null, {
headers: new HttpHeaders({
'Authorization': 'Bearer ' + token
})
}).subscribe((successResp) => {
resolve(successResp);
},
(errorResp) => {
resolve(errorResp);
}
);
我收到类似的错误
Access to XMLHttpRequest at 'http://localhost:8080/api/auth/userdetails' from origin 'http://localhost:4200' 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.
zone-evergreen.js:2845 POST http://localhost:8080/api/auth/userdetails net::ERR_FAILED
这是网络安全配置器
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable().authorizeRequests()
.antMatchers("/authenticate").permitAll().anyRequest()
.authenticated().and().exceptionHandling()
.authenticationEntryPoint(jwtAuthenticationEntryPoint)
.and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.addFilterBefore(customJwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
这是 WebMvcConfigurer
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD", "TRACE", "CONNECT")
.allowedOrigins("http://localhost:4200");
}
请帮帮我。
为什么它在邮递员中工作而不在 Angular 中工作。
我错过了什么?
解决方案
将 CORS 与 spring security 一起使用时,您必须在安全配置中再执行一步才能使其正常工作。发生这种情况是因为必须首先处理 CORS。
https://www.baeldung.com/spring-cors#cors-with-spring-security
在您的安全配置中,您必须在其余逻辑之前调用 cors
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.cors().and()...
}
推荐阅读
- c# - 为多个成员使用 AutoMapper 自定义值解析器
- django - 如何修复 AssertionError 200!=302
- kubernetes - 两个 PersistentVolumeClaims 的状态之一是“待定”
- python-3.x - selenium 有没有办法将我的用户名和密码输入到浏览器的提示符中?
- excel - Excel VBA 从其他 Excel 文件中收集数据并将它们粘贴到 Masterfile
- javascript - 如果在对象数组中将对象设置为未定义,则返回 true
- c# - EntityFramework 无法正确保存更改
- powershell - Rename log file on remote computers if greater than 80MB
- sql - 如何修复外键约束
- java - 显示字符串没有第 6 个字符时出现问题