SpringBoot 通过拦截器验证Referer 防御CSRF攻击

CSRF跨站点请求伪造
通过Referer识别 进行CSRF防御 在springboot项目中 ,通过增加拦截器,识别refer 即可防御csrf 攻击。
配置自己信任的白名单“Referer” 新建拦截器配置。
        
新建拦截器配置

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Autowired
    private RefererInterceptor refererInterceptor;

    /**
     * 添加过滤器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(refererInterceptor).addPathPatterns("/**").excludePathPatterns("/", "/login", "/logout");
    }
}


新建拦截器

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.MalformedURLException;

@Component
public class RefererInterceptor extends HandlerInterceptorAdapter {
    /**
     * 白名单
     */
    private String[] refererDomain = new String[]{"www.baidu.com", "xxx.xxx.xx"};
    /**
     * 是否开启referer校验
     */
    private Boolean check = true;


    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        if (!check) {
            return true;
        }
        String referer = req.getHeader("referer");
        String host = req.getServerName();
        // 验证非get请求
        if (!"GET".equals(req.getMethod())) {
            if (referer == null) {
                // 状态置为404
                resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return false;
            }
            java.net.URL url = null;
            try {
                url = new java.net.URL(referer);
            } catch (MalformedURLException e) {
                // URL解析异常,也置为404
                resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return false;
            }
            // 首先判断请求域名和referer域名是否相同
            if (!host.equals(url.getHost())) {
                // 如果不等,判断是否在白名单中
                if (refererDomain != null) {
                    for (String s : refererDomain) {
                        if (s.equals(url.getHost())) {
                            return true;
                        }
                    }
                }
                return false;
            }
        }
        return true;
    }
}

 

发布者:songJian   点击数:863   发布时间:2024-01-08 17:46:19   更新时间:2024-01-09 09:28:12
正在加载评论...
相关文章