0


JAVA-添加HTTP响应头预防XXS攻击

方案一:在web.config中配置

<customHeaders>
    <!--检测到目标X-Content-Type-Options响应头缺失-->
    <add name="X-Content-Type-Options" value="nosniff" />
    <!--检测到目标X-XSS-Protection响应头缺失-->
    <add name="X-XSS-Protection" value="1;mode=block" />
    <!--检测到目标Content-Security-Policy响应头缺失-->
    <add name="Content-Security-Policy" value="default-src 'self'" />
    <!--检测到目标Strict-Transport-Security响应头缺失-->
    <add name="Strict-Transport-Security" value="max-age=31536000" />
    <!--检测到目标Referrer-Policy响应头缺失-->
    <add name="Referrer-Policy" value="origin-when-cross-origin" />
    <!--检测到目标X-Permitted-Cross-Domain-Policies响应头缺失-->
    <add name="X-Permitted-Cross-Domain-Policies" value="master-only" />
    <!--检测到目标X-Download-Options响应头缺失-->
    <add name="X-Download-Options" value="noopen" />
    <!--点击劫持:X-Frame-Options未配置-->
    <add name="X-Frame-Options" value="SAMEORIGIN" />
</customHeaders>

方案二:自定义filter

import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义过滤器,继承OncePerRequestFilter并实现doFilterInternal方法
 */
public class Myfilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        // 设置响应头,预防HTTP响应头缺失漏洞
        httpServletResponse.setHeader("X-Permitted-Cross-Domain-Policies", "master-only");
        httpServletResponse.setHeader("X-XSS-Protection", "1;mode=block");
        httpServletResponse.setHeader("X-Download-Options", "noopen");
        httpServletResponse.setHeader("X-Content-TYpe-OPtions", "nosniff");
        httpServletResponse.setHeader("Content-Security-Policy", "default-src 'self'");
        httpServletResponse.setHeader("X-Frame-Options", "SAMEORIGIN");

        // 过滤放行
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
 
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;

/**
 * 自定义过滤器配置类
 */
@Configuration
public class FilterCOnfiguration {

    /**
     * 注册MyFilter到Spring Ioc容器
     * @return
     */
    @Bean
    FilterRegistrationBean<Myfilter> registrationBean() {
        FilterRegistrationBean<Myfilter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new Myfilter());// 设置过滤器
        bean.setOrder(-1);// 设置优先级,数字越小优先级越高
        bean.setName("MyFilter");// 设置过滤器别名
        bean.setUrlPatterns(Arrays.asList("/*"));// 设置过滤路径
        return bean;
    }

}
标签: web安全

本文转载自: https://blog.csdn.net/qq_36639124/article/details/129712038
版权归原作者 赖木子 所有, 如有侵权,请联系我们删除。

“JAVA-添加HTTP响应头预防XXS攻击”的评论:

还没有评论