后端SpringSecurity+vue前端axios+uni-app解决跨站点请求伪造CSRF

1.1.SpringSecurity配置,public class SecurityConfig extends WebSecurityConfigurerAdapter

 @Override
    protected void configure(HttpSecurity http) throws Exception {
     //code...
     http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    }

2.vue组件axios,config.js,默认支持也可以不配置

axios.defaults.withCredentials = true // 设置cross跨域,并设置访问权限,允许跨域
axios.defaults.crossDomain = true
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8' // 设置post请求头
axios.defaults.headers.put['Content-Type'] = 'application/json;charset=utf-8' // 设置post请求头
axios.defaults.timeout = 60000 // 请求超时响应
axios.defaults.responseType = 'json' // 请求超时响应
axios.defaults.xsrfCookieName = 'XSRF-TOKEN'
axios.defaults.xsrfHeaderName = 'X-XSRF-TOKEN'

3.小程序请求框架为uni-app,由于不带cookie,可以配置CSRF小程序路径放开,小程序接口统一放在/miniapi路径下,对小程序统一鉴权有兴趣的我可以再写一篇

4.csrf按请求路径URL过滤,AntPathRequestMatcher实现/miniapi路径下请求不进行拦截

 @Override
    protected void configure(HttpSecurity http) throws Exception {
     //code...
     http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
http.csrf().requireCsrfProtectionMatcher(new CsrfSecurityRequestMatcher());
    }
public class CsrfSecurityRequestMatcher  implements RequestMatcher{
	private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
	private AntPathRequestMatcher antPathRequestMatcher=new AntPathRequestMatcher("/miniapi/**");

	@Override
	public boolean matches(HttpServletRequest request) {
		if(allowedMethods.matcher(request.getMethod()).matches()){
			return false;
		}
		boolean b = !antPathRequestMatcher.matches(request);
		return b;
	}
}

5.多环境支持
跨域只是为了保证生产环境安全,开发环境为了方便swagger使用和自动化测试,可以配置不开启

csrf: false
    @Value("${csrf}")
    private Boolean csrf;
  // 启用CSRF
        if(csrf){
            http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
            http.csrf().requireCsrfProtectionMatcher(new CsrfSecurityRequestMatcher());
        }else {
            http.csrf().disable();
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值