1.cookie與session的關係java
Session 信息都是放在內存的,第一次建立Session的時候,服務端會在 Cookie 裏面記錄一個Session ID,以JSESSIONID的方式來保存,之後每次請求把這個會話ID發送到服務器,根據Session ID服務器就知道是誰了,因此session相對是安全的(Session ID能夠被劫持與僞造,因此Session ID不能是固定的),假若Cookie被禁用,那麼須要url重寫來解決該問題(web
在路徑後面自動拼接sessionId)。spring
url重寫:String path = resp.encodeURL(
"path"
)(轉發);
數據庫String path =
response.encodeRedirectURL("path")(重定向
);
Session ID防止被劫持跨域
方式1:每次在接受Session ID後進行銷燬,而後將其中的數據保存在新的Session,也不是很可靠,只是相對可靠,能夠利用間隙時間劫持瀏覽器
方式2:設置httpOnly屬性,httpOnly是cookie的擴展屬性,並不包含在servlet2.x的規範裏,所以一些javaee應用服務器並不支持httpOnly,針對tomcat >6.0.19或者>5.5.28的版本才支持httpOnly屬性tomcat
使用方法安全
<Context useHttpOnly="true"> ... </Context>
或服務器
response.setHeader( "Set-Cookie", "name=value; HttpOnly");
2. session跨域cookie
緣由:默認session是不能跨域的
什麼是域
在應用模型,一個完整的,有獨立訪問路徑的功能集合稱爲一個域。例如百度下的若干的域,如:搜索引擎(www.baidu.com),百度貼吧(tie.baidu.com),百度知道(zhidao.baidu.com),百度地圖(map.baidu.com)等。域信息,有時也稱爲多級域名。域的劃分: 以IP,端口,域名,主機名爲標準,實現劃分。
什麼是跨域
客戶端請求的時候,請求的服務器,不是同一個IP,端口,域名,主機名的時候,都稱爲跨域。
什麼是session跨域
Session跨域就是摒棄了系統(Tomcat)提供的Session,而使用自定義的相似Session的機制來保存客戶端數據的一種解決方案。
實現方法的原理
經過設置cookie的domain來實現cookie的跨域傳遞。在cookie中傳遞一個自定義的session_id。這個session_id是客戶端的惟一標記。將這個標記做爲key,將客戶端須要保存的數據做爲value,在服務端進行保存(數據庫保存或NoSQL保存)。這種機制就是Session的跨域解決。
代碼實現
@RequestMapping("/test")
public String test(HttpServletRequest request, HttpServletResponse response){
//cookieName名
String cookieName="custom_global_session_id";
String encodeString="UTF-8";
//獲取cookieName名對應的cookieValue的值
String cookieValue = CookieUtils.getCookieValue(request, cookieName, encodeString);
//假如爲null或者「」,使用UUID隨機產生一個32位的隨機字符串
if(null == cookieValue || "".equals(cookieValue.trim())){
System.out.println("無cookie,生成新的cookie數據");
cookieValue = UUID.randomUUID().toString();
}
// 根據cookieValue訪問數據存儲,獲取客戶端數據。
CookieUtils.setCookie(request, response, cookieName, cookieValue, 0, encodeString);
return "/ok.jsp";
}
public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) { Cookie[] cookieList = request.getCookies(); if (cookieList == null || cookieName == null) { return null; } String retValue = null; try { for (int i = 0; i < cookieList.length; i++) { if (cookieList[i].getName().equals(cookieName)) { retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString); break; } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return retValue; } public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, String encodeString) { doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString); } private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, String encodeString) { try { if (cookieValue == null) { cookieValue = ""; } else { cookieValue = URLEncoder.encode(cookieValue, encodeString); } Cookie cookie = new Cookie(cookieName, cookieValue); if (cookieMaxage > 0) cookie.setMaxAge(cookieMaxage); if (null != request) {// 設置域名的cookie String domainName = getDomainName(request);//獲取域名 if (!"localhost".equals(domainName)) { cookie.setDomain(domainName);//domain的含義爲域 } } cookie.setPath("/");//可在同一應用服務器內共享方法,能夠在webapp文件夾下的全部應用共享cookie response.addCookie(cookie); } catch (Exception e) { e.printStackTrace(); } } private static final String getDomainName(HttpServletRequest request) { String domainName = null; // 獲取完整的請求URL地址。 String serverName = request.getRequestURL().toString(); if (serverName == null || serverName.equals("")) { domainName = ""; } else { serverName = serverName.toLowerCase(); if (serverName.startsWith("http://")){ serverName = serverName.substring(7); } else if (serverName.startsWith("https://")){ serverName = serverName.substring(8); } final int end = serverName.indexOf("/"); // .test.com www.test.com.cn/sso.test.com.cn/.test.com.cn spring.io/xxxx/xxx serverName = serverName.substring(0, end); final String[] domains = serverName.split("\\."); int len = domains.length; if (len > 3) { domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1]; } else if (len <= 3 && len > 1) { domainName = "." + domains[len - 2] + "." + domains[len - 1]; } else { domainName = serverName; } } if (domainName != null && domainName.indexOf(":") > 0) { String[] ary = domainName.split("\\:"); domainName = ary[0]; } return domainName; }
備註:
set-cookie雖然在響應頭中存在,可是在跨域的時候出於安全考慮,該頭會被瀏覽器忽略,並不會產生真實的cookie,而Cookie 的domain屬性設置域以後,那麼子域能夠訪問父域的cookie,而父域不能夠訪問子域的cookie,能夠說cookie的domain訪問權限是向下繼承的,固然其它域名跨域名訪問也是不能夠的。注意:假若將domain設置爲com.cn,可是f.com.cn是不會接收domain爲com.cn的cookie,domain設置爲b.e.f.com.cn或.b.e.f.com.cn沒有區別,session是保存在內存中的,由Session ID取值。跨域設計的思想也是子域能夠訪問父域。
而session共享是經過cookie.setPath("/")設置;//可在同一應用服務器內共享方法,能夠在webapp文件夾下的全部應用共享cookie