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

    技术2024-07-17  67

    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(); }
    Processed: 0.014, SQL: 9