1. 程式人生 > >【Webview相關問題】登陸失敗之cookie陷阱

【Webview相關問題】登陸失敗之cookie陷阱

什麼問題呢?

又是一個android獨有的問題。
12306一直登陸不上,但是在某些手機上又可以。
檢查請求資料,一個不查

什麼原因呢?

在12306登陸的時候,會有這麼個熟悉的驗證碼出現。
這裡寫圖片描述

驗證碼及之後的互動時序圖如下:

這裡寫圖片描述

如上圖,在打碼完成後所傳送的12306請求必須帶上驗證碼下發的cookie A, 但實際上使用的cookie還是之前的cookie ,也就是說驗證碼圖片下載時所下發的cookie沒有儲存到webview的cookieManager中。

來說說cookie

主要作用是:使用者識別及狀態管理,Web為了管理使用者的狀態會把一些資料臨時寫入到使用者的計算機內。
上面的情況就是把使用者的某一次登陸請求和前面所下發的驗證碼圖片通過cookie來進行前後銜接。

最終原因

android5.0及以上版本 限制接受第三方cookie

如何解決?

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        CookieManager cookieManager = CookieManager.getInstance();                  
        cookieManager.setAcceptThirdPartyCookies(mDelegate.mWebView, enable);
}

什麼叫ThirdPartyCookies?

What is a (third-party) cookie?

A cookie is a small script placed on the hard drive of your computer by the server of a website that you visit. The cookie is placed there for the purpose of recognising your specific browser / computer combination, were you to return to the same site.

All cookies have an owner which tells you who the cookie belongs to. The owner is the domain specified in the cookie.

The word “party” refers to the domain as specified in cookie; the website that is placing the cookie. So, for example, if you visit widgets.com and the domain of the cookie placed on your computer is widgets.com, then this is a first-party cookie. If, however, you visit widgets.com and the cookie placed on your computer says stats-for-free.com, then this is a third-party cookie.

Opentracker provides services that allow the companies and websites to track their visitors with first-party cookies.

簡單來說,每個cookie都對應有一個宿主,這個宿主就是set-cookie時候對應的域名,當你訪問的是A域名頁面,但是cookie的宿主是B域名。對A來說這個cookie就是ThirdPartyCookies. 阻止跨域訪問也是為了安全起見。

參考: