所以我有一个奇怪的情况。几周前,我在我的春季后端通过angular访问了其他端点。在控制器类顶部添加@CrossOrigin(origins = arrayOf("http://localhost:4200"))
后,它起作用了。
但是,在客户端上添加了一些Spring安全性和一些http拦截器后,它停止工作了,说
Access to XMLHttpRequest at 'http://localhost:8080/v1/backend/calculationtype/' from origin 'http://localhost:4200' has been blocked by CORS policy
我不知道这怎么可能。授权后,我将获得一个Bearer令牌,该令牌通过Interceptor添加到httpHeader中。使用Postman时,一切正常。我正在使用OAuth2。
我将展示一些课程。
token.interceptor.ts:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.temp.getToken()}` //contains the Bearer token
}
});
console.log(request);
return next.handle(request);
}
我正在使用console.log
打印我正在发送的请求。请求的标头包含值为Authorization
的键Bearer e23..........
。在邮递员中使用这些值,就可以了。
CalculationTypeController.kt(我使用的是Kotlin而不是Java):
@CrossOrigin(origins = arrayOf("http://localhost:4200")) //this line worked before
@RestController
@RequestMapping(value = ["v1/backend/calculationtype/"])
class CalculationTypeController() {
@RequestMapping(method = [RequestMethod.POST], produces = [MediaType.APPLICATION_JSON_VALUE])
fun addCalculationType(@RequestBody calcDTO: CalcDTO): CalcuDTO {
some stuff happening...
}
}
使用身份验证时,我必须添加一个proxy.conf.json
,但是我不需要它来从端点获取数据。但是,就在这里。
proxy.conf.json:
{
"/oauth/*": {
"target": "http://localhost:8080",
"secure": false,
"changeOrigin":true,
"logLevel": "debug"
},
"/v1/*": {
"target": "http://localhost:8080",
"secure": false,
"changeOrigin":true,
"logLevel": "debug"
}
}
谁可以给我一些建议或告诉我这里发生了什么?谢谢您的帮助!
答案 0 :(得分:1)
尝试为您的项目启用CORS,在Spring项目中创建此类:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
或者如果您有Spring Boot应用程序:
@Configuration
public class CORSConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
};
}
}
两个类都是@Configuration
,因此它们将作为应用服务器启动的一部分运行
答案 1 :(得分:1)
如果使用Spring Security,则需要执行一些其他步骤。否则,Spring Security将在请求到达Spring MVC之前拒绝它。
有关详细信息,请参见the related section in Spring Security docs。
答案 2 :(得分:1)
我假设您在angular.json中添加了proxy.config
:
...
"serve": {
"proxyConfig": "proxy.config.js"
}
...
proxy.config.js
const PROXY_CONFIG = [
{
"context": ['/oauth/*']
"target": "http://localhost:8080",
"secure": false,
"changeOrigin":true,
"logLevel": "debug"
},
{
"context": ['/v1/backend']
"target": "http://localhost:8080",
"secure": false,
"changeOrigin":true,
"logLevel": "debug"
},
]