【发布时间】:2019-06-18 06:59:52
【问题描述】:
我正在尝试在我的 Java Spring 项目上设置 CORS。
另外,我有一个带有登录页面的 Angular CLI 应用程序,我想使用我的 Spring API 对用户进行身份验证。
我在客户端收到错误
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.
我在服务器日志中得到了这个:
No mapping found for HTTP request with URI [/authenticateUser]
我尝试了其他线程的一些示例,但客户端错误没有改变,所以我有点困惑在哪里配置 cors
我有一个 AppSecurityConfig 类 extends WebSecurityConfigurerAdapter
@Configuration
@EnableWebSecurity
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
User.UserBuilder users = User.withDefaultPasswordEncoder();
auth.inMemoryAuthentication()
.withUser(users.username("user1").password("password").roles("ROLE1"))
.withUser(users.username("user2").password("password").roles("ROLE2"))
.withUser(users.username("user3").password("password").roles("ROLE3"));
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors()
.and()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/loginPageUrl")
.loginProcessingUrl("/authenticateUser")
.permitAll();
}
我的 Angular 服务发出请求:
authenticateUser(json: any) {
return this.http.post('http://localhost:8085/authenticateUser'
, json, {headers : new HttpHeaders()
.set('Authorization', '')
});
}
传入的json是:
{ username: this.username, password: this.password }
将以下方法添加到我的 AppSecurityConfig 类解决了“请求的资源上不存在“无 'Access-Control-Allow-Origin' 标头”错误。
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
configuration.addAllowedHeader("content-type");
configuration.addAllowedHeader("Access-Control-Allow-Origin");
configuration.addAllowedHeader("Authorization");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
【问题讨论】:
标签: java angular spring spring-security