检测到会话cookie中缺少HttpOnly属性

文章目录

  • 配置过滤器,过滤不规范的url。具体代码:
    • 配置类
    • 过滤器

配置过滤器,过滤不规范的url。具体代码:

配置类

public class MyPublishConfig implements WebMvcConfigurer  {

    /**
     * 配置过滤器
     * @return
     */
    @Bean
    public FilterRegistrationBean myFilter(){
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        // 设置filter
        registrationBean.setFilter(new MyPublishFilter());
        // 设置filter需要拦截的地址
        registrationBean.setUrlPatterns(Arrays.asList("url地址!!!!"));
        return registrationBean;
    }
}

过滤器

public class MyPublishFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            // 解决安全漏洞:检测到会话cookie中缺少HttpOnly属性
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse resp = (HttpServletResponse) response;
            Cookie[] cookies = req.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    String value = cookie.getValue();
                    StringBuilder builder = new StringBuilder();
                    builder.append("JSESSIONID=" + value + "; ");
                    builder.append("Secure; ");
                    builder.append("HttpOnly; ");
                    Calendar cal = Calendar.getInstance();
                    cal.add(Calendar.HOUR, 1);
                    Date date = cal.getTime();
                    Locale locale = Locale.CHINA;
                    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss",
                            locale);
                    builder.append("Expires=" + sdf.format(date));
                    resp.setHeader("Set-Cookie", builder.toString());
                }
                chain.doFilter(request, response);
            }
    }

    @Override
    public void destroy() {

    }
}

你可能感兴趣的:(安全漏洞)