1.cookie與session的關系
Session 信息都是放在內存的,第一次創建Session的時候,服務端會在 Cookie 里面記錄一個Session ID,以JSESSIONID的方式來保存,以后每次請求把這個會話ID發送到服務器,根據Session ID服務器就知道是誰了,所以session相對是安全的(Session ID可以被劫持與偽造,所以Session ID不能是固定的),倘若Cookie被禁用,那么需要url重寫來解決該問題(
在路徑后面自動拼接sessionId)。
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屬性
使用方法
<Context useHttpOnly="true"> ... </Context>
或
response.setHeader( "Set-Cookie", "name=value; HttpOnly");
2. session跨域
原因:默認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