防止服务端产生的cookie被客户端的cookie替换掉

今天碰到一个问题

服务端产生的cookie被客户端的cookie替换掉了

解决办法:

把Cookie的HttpOnly这个属性设置为true

下面是两种添加Cookie的方法

Cookie类

	/**
	 * 根据部署路径,将cookie保存在根目录。
	 * 
	 * @param request
	 * @param response
	 * @param name cookie名
	 * @param value	cookie值
	 * @param expiry //最大生存时间(秒,0代表删除,-1代表与浏览器会话一致)
	 * @param domain 域
	 * @param path 路径
	 * @param secure 是否为安全协议信息
	 * @param isHttpOnly 是否为HttpOnly(如果未设置,可以被客户端的cookie替换)
	 * @param comment 注释
	 * @return
	 */
	public static Cookie addCookie(HttpServletRequest request, HttpServletResponse response, String name, 
			String value, Integer expiry, String domain, String path, Boolean secure, Boolean isHttpOnly, String comment) {
		Cookie cookie = new Cookie(name, value);
		if (expiry != null) {
			cookie.setMaxAge(expiry);
		}
		if (StringUtils.isNotBlank(domain)) {
			cookie.setDomain(domain);
		}
		if(secure != null){
			cookie.setSecure(secure);
		}
		if(isHttpOnly != null){
			cookie.setHttpOnly(isHttpOnly);
		}
		if(StringUtils.isNotEmpty(comment)){
			cookie.setComment(comment);
		}
		cookie.setPath(path);
		response.addCookie(cookie);
		return cookie;
	}

response.addHeader()

	/**
	 * 具有SameSite属性
	 * @param request
	 * @param response
	 * @param name
	 * @param value
	 * @param expiry
	 * @param domain
	 * @param path
	 * @param secure
	 * @param isHttpOnly
	 * @param sameSite
	 * @param comment
	 */
	public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name, 
			String value, Integer expiry, String domain, String path, Boolean secure, Boolean isHttpOnly, String sameSite, String comment) {
		StringBuilder buffer = new StringBuilder();
        buffer.append(name).append("=").append(value).append(";");
        if(expiry != null){
        	/*
        	 * Fri Oct 21 08:36:45 UTC 2016
        	 * Cookie expires 时间格式
        	 */
         	String expires = DateUtils.formatToString(DateFormat.EEE__MMM__dd__HH_mm_ss__z__yyyy, DateUtils.dateAdd(new Date(), expiry, Calendar.SECOND), Locale.US, TimeZone.getTimeZone("UTC"));
        	buffer.append("Expires=").append(expires).append(";");
    		/* 
    		 * IE中不支持这个属性
    		 * buffer.append("Max-Age=").append(expiry).append(";");
    		 */
        }
        if (domain != null) {
            buffer.append("domain=").append(domain).append(";");
        }
        if (path != null) {
            buffer.append("path=").append(path).append(";");
        }
        if (secure != null && secure) {
            buffer.append("secure;");
        }
        if (isHttpOnly != null && isHttpOnly) {
            buffer.append("HttpOnly;");
        }
        if(StringUtils.isNotEmpty(sameSite)){
        	buffer.append("SameSite=").append(sameSite).append(";");
        }
        response.addHeader("Set-Cookie", buffer.toString());
	}


你可能感兴趣的:(JavaScript,Java)