[英]Cors Auth SpringBoot
我正在使用 springboot 和 angular。 尝试使用 JWT 登录,当使用邮递员发送 http 时,请求没问题,但是当尝试使用 Angular 发送相同的 http 时,我收到下一个错误:
从源 'http://localhost:4200' 访问 XMLHttpRequest at 'http://localhost:8080/login' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP好的状态。
和
zone-evergreen.js:2845 POST http://localhost:8080/login net::ERR_FAILED
当我发送除登录以外的请求时,它们工作正常我知道需要一个 cors 所以代码是下一个:
@EnableGlobalMethodSecurity(securedEnabled = true)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and().csrf().disable().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().cors();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
org.springframework.web.cors.CorsConfiguration configuration = new org.springframework.web.cors.CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
configuration.setAllowedMethods(Arrays.asList("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
但错误是一样的。
您可以在 angular 应用程序中使用 proxy.conf.json。
这是示例proxy.conf.json
{
"/api/*": {
"target": "http://localhost:8080",
"secure": false,
"logLevel": "debug",
"pathRewrite": {
"^/api" : ""
}
}
}
然后你可以使用http://localhost:4200/api/path-be
你的 BE
http://localhost:4200
是您的 Angular 应用程序。 /api
如果您向/api/*
发出请求,那么角度代理配置将重定向到您在proxy.conf.json
定义的proxy.conf.json
记得将proxy.conf.json
添加到你的angular.json
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "angular-hands-on:build",
"proxyConfig": "proxy.conf.json"
},
重启你的 Angular 应用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.