iron ajax请求导致spring boot出现cors问题
目前,我在对使用SpringBoot2开发的服务器进行ajax调用(使用Polymer 2的iron ajax元素)时面临CORS问题 通过Postman执行post请求/登录会返回预期结果,但是,使用Safari或Chrome等浏览器会导致以下错误: 加载失败:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“访问控制允许来源”标头。因此,不允许访问源“”。响应的HTTP状态代码为403 我在后端的配置如下所示:iron ajax请求导致spring boot出现cors问题,ajax,spring-boot,spring-security,cors,polymer-2.x,Ajax,Spring Boot,Spring Security,Cors,Polymer 2.x,目前,我在对使用SpringBoot2开发的服务器进行ajax调用(使用Polymer 2的iron ajax元素)时面临CORS问题 通过Postman执行post请求/登录会返回预期结果,但是,使用Safari或Chrome等浏览器会导致以下错误: 加载失败:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“访问控制允许来源”标头。因此,不允许访问源“”。响应的HTTP状态代码为403 我在后端的配置如下所示: @Configuration @EnableWebSecurity p
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/users").permitAll()
.antMatchers(HttpMethod.POST, "/login").permitAll()
.anyRequest().authenticated()
.and()
// We filter the api/login requests
.addFilterBefore(new JWTLoginFilter("/login", authenticationManager()),
UsernamePasswordAuthenticationFilter.class)
// And filter other requests to check the presence of JWT in header
.addFilterBefore(new JWTAuthenticationFilter(),
UsernamePasswordAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// Create a default account
auth.inMemoryAuthentication()
.passwordEncoder(NoOpPasswordEncoder.getInstance())
.withUser("admin")
.password("password")
.roles("ADMIN");
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
ajax调用设置如下:
<iron-ajax
id="postLoginAjax"
method="post"
headers='{"access-control-allow-origin": "*"}' // Tried with and without
content-type="application/json"
handle-as"json"
on-touch="touch"
on-response="handleUserResponse"
on-error"handleUserError">
</iron-ajax>
基于其他SO帖子,我已经实现了Bean,但是仍然没有成功
编辑:
此外,在上建议的全局cors设置不会产生我想要的结果。我假设是因为它依赖于mvc依赖关系,而我没有使用它
提前感谢您的帮助,
Chris您应该尝试将
with credentials
属性添加到您的iron ajax
元素中。您好@codeMonkey,我会尽快尝试一下。同时,我在服务器端修复了它。将在本周末更新此内容。我也会确认你的建议。我在polymer 2.0中遇到了同样的问题,它有弹簧靴。