Hal*_*Dev 25 java spring spring-mvc cors
更新:现在回顾一年多以后,我正在给予更新希望,这将有助于其他人.
Spring IO建议对普通用户可以由浏览器处理的任何请求使用CSRF保护.如果您只创建非浏览器客户端使用的服务,则可能需要禁用CSRF保护.由于我的应用程序是API并且将由浏览器处理,因此禁用CSRF不是一种方法.
默认情况下,使用Spring Boot启用CSRF,您需要添加以下代码以添加CSRF存储库和过滤器,以将CSRF令牌添加到您的http请求中.(解决方案来自此处POST请求中的无效CSRF令牌)
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/assets/**", "/templates/**", "/custom-fonts/**", "/api/profile/**", "/h2/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/login?logout")
.permitAll()
.and()
.csrf().csrfTokenRepository(csrfTokenRepository())
.and()
.addFilterAfter(csrfHeaderFilter(), SessionManagementFilter.class); // Register csrf filter.
}
Run Code Online (Sandbox Code Playgroud)
过滤器和CsrfToken存储库部分:
private Filter csrfHeaderFilter() {
return new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
if (csrf != null) {
Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
String token = csrf.getToken();
if (cookie == null || token != null
&& !token.equals(cookie.getValue())) {
// Token is being added to the XSRF-TOKEN cookie.
cookie = new Cookie("XSRF-TOKEN", token);
cookie.setPath("/");
response.addCookie(cookie);
}
}
filterChain.doFilter(request, response);
}
};
}
private CsrfTokenRepository csrfTokenRepository() {
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
return repository;
}
Run Code Online (Sandbox Code Playgroud)
原始问题我在2016年2月回复
我正致力于使用Spring 4为Spring引导RESTful API提供全局CORS支持.
我正在关注官方的Spring Boot Doc(https://spring.io/guides/gs/rest-service-cors/)并将其添加到我的应用程序中:
public class SomeApiApplication {
public static void main(String[] args) {
SpringApplication.run(SomeApiApplication.class, args);
}
//Enable Global CORS support for the application
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:8080")
.allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD")
.allowedHeaders("header1", "header2") //What is this for?
.allowCredentials(true);
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么只有GET正在工作,对于其余的http调用,我收到一条错误消息,说"无效的CORS请求".我在设置中是否遗漏了什么?如果我的设置不正确,GET也不应该正常工作.我很困惑.
小智 9
我有同样的问题 - GET工作.POST没有.我在CORS域中寻找答案,但最终发现它是由于CSRF保护.为了解决这个问题,我在安全配置中禁用了CSRF保护:
@Configuration @EnableWebSecurity
public class SpringWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
**.csrf().disable()** //TODO: for production, must be reconfigured in order to disable only in specific cases. This line was added because without it, HTTP POST requests did not work.
.authorizeRequests()
.antMatchers("/api/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
Run Code Online (Sandbox Code Playgroud)
确保您了解自己在做什么:https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html
我有一个类似的问题,只有HEAD GET和POST为我工作。我发现它addCorsMappings具有的默认值allowedMethods。
该代码对我有用:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("*")
.allowedOrigins("http://localhost:4200");
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
尝试将allowedOrigins方法更改为.allowedOrigins("*").邮差是一个扩展,它运行在另一个"主机".
但请确保您了解其影响:https://spring.io/understanding/CORS
| 归档时间: |
|
| 查看次数: |
33146 次 |
| 最近记录: |