/**
* @param req
* @param resp
* @Description 设置响应头
* @Throws
* @Return void
* @Date 2021-07-06 19:17:16
* @Author WangKun
**/
public static void setResponseHeader(HttpServletRequest req, HttpServletResponse resp) {
try {
req.setCharacterEncoding("UTF-8");
// 响应头设置,预防HTTP响应头缺失漏洞
resp.setHeader("X-Frame-Options", "SAMEORIGIN");
resp.setHeader("Strict-Transport-Security", "max-age=31536000; includeSubdomains; preload");
String origin = req.getHeader("Origin");
if (origin == null) {
origin = req.getHeader("Referer");
}
resp.setHeader("Referrer-Policy", origin);
resp.setHeader("Content-Security-Policy", "default-src 'self'");
resp.setHeader("X-Permitted-Cross-Domain-Policies", "master-only");
resp.setHeader("X-XSS-Protection", "1;mode=block");
resp.setHeader("X-Download-Options", "noopen");
resp.setHeader("X-Content-TYpe-Options", "nosniff");
resp.setHeader("Access-Control-Allow-Origin", origin);
resp.setHeader("Access-Control-Allow-Credentials", "true");
resp.setHeader("Access-Control-Max-Age", "3600");
// 判断请求方法是否为OPTIONS
if ("OPTIONS".equals(req.getMethod())) {
// 设置响应头信息,禁止OPTIONS请求
resp.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, HEAD");
resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
} else {
resp.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, HEAD,OPTIONS");
}
resp.setHeader("Access-Control-Allow-Headers", "User-Agent,Origin,Cache-Control,Content-type,Date,Server,withCredentials,AccessToken");
resp.setHeader("Access-Control-Expose-Headers", "accession");
resp.setHeader("Access-Control-Request-Headers", "accession");
resp.setHeader("Expires", "-1");
resp.setHeader("Cache-Control", "no-cache");
resp.setHeader("pragma", "no-cache");
resp.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
resp.setHeader("Cross-Origin-Opener-Policy", "same-origin");
// resp.setHeader("Cross-Origin-Resource-Policy", "same-origin");
// resp.setHeader("Cross-Origin-Resource-Policy","same-site");
resp.setHeader("Cross-Origin-Resource-Policy", "cross-origin");
resp.setHeader("Permissions-Policy", "geolocation=(self)");
// resp.setHeader("Clear-Site-Data", "cache,cookies");
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
String value = cookie.getValue();
String builder = cookie.getName() + "=" + value + ";" +
"Secure;" +//Cookie设置Secure标识
"HttpOnly;";//Cookie设置HttpOnly
resp.addHeader("Set-Cookie", builder);
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
响应头设置,预防HTTP响应头缺失漏洞
于 2024-01-19 12:30:21 首次发布