方案一:在web.config中配置文章来源:https://www.toymoban.com/news/detail-668187.html
<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文章来源地址https://www.toymoban.com/news/detail-668187.html
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;
}
}
到了这里,关于JAVA-添加HTTP响应头预防XXS攻击的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!