专栏文章
1.springboot前后端分离项目集成Security框架和JWT完成用户校验
前言
在当今的Web开发中,跨域请求成为了无法回避的问题。由于浏览器的同源策略限制,如果我们的后端服务和前端应用不在同一个域名下,那么默认情况下浏览器是不允许跨域请求的。这就导致了在开发过程中可能会遇到跨域请求被浏览器拦截的问题。
为了解决跨域请求的问题,我们可以使用CORS(跨域资源共享)机制。通过在后端应用中添加相关的CORS头信息,我们可以告诉浏览器允许来自其他域的请求访问我们的接口。
在本篇文章中,我们将介绍如何使用Spring Boot来处理跨域请求。我们将使用一个自定义的CORSFilter过滤器来添加必要的CORS头信息,以允许跨域请求的访问。
1. 跨域之CorsFilter介绍
CorsFilter 是 Spring 框架提供的一个用于处理跨域请求的过滤器。在开发中,我们常常需要处理前端发来的跨域请求,CorsFilter 就可以帮助我们实现这一功能。
CorsFilte主要用于设置跨域请求的响应头,以允许跨域请求能够被成功处理
- Access-Control-Allow-Origin:允许访问的源地址;
- Access-Control-Allow-Methods:允许访问的请求方法;
- Access-Control-Allow-Headers:允许访问的请求头;
- Access-Control-Allow-Credentials:是否允许发送 Cookie 等身份凭证;
- Access-Control-Max-Age:缓存预检请求的时间。
2. 项目内配置CorsConfig
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* @author 方磊
*/
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 允许cookies跨域
corsConfiguration.setAllowCredentials(true);
// #允许向该服务器提交请求的URI,*表示全部允许,自定义可以添加多个
corsConfiguration.addAllowedOrigin("*");
// #允许访问的头信息,*表示全部,可以添加多个
corsConfiguration.addAllowedHeader("*");
// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
corsConfiguration.setMaxAge(1800L);
// 允许提交请求的方法,*表示全部允许,一般OPTIONS,GET,POST三个够了
corsConfiguration.addAllowedMethod("*");
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
}
3. 总结
配置CorsFIlter可解决项目跨域问题和项目启动时报错
***************************
APPLICATION FAILED TO START
***************************
Description:
Field corsFilter in com.wyj.yjwu.config.SecurityConfig required a bean of type 'org.springframework.web.filter.CorsFilter' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'org.springframework.web.filter.CorsFilter' in your configuration