Make Android WebView not store cookies or passwords

Thilo picture Thilo · Mar 23, 2011 · Viewed 44.6k times · Source

I use an Android WebView for Twitter OAuth: Twitter asks the user to log in and authorize the application, I retrieve the access token and persist it in my application.

I have no need (and do not) store the user password, but the WebView keeps Twitter's cookies around, and it also asks the user if he wants it to remember the password. As a result of this, even after the de-authorizes the application via his Twitter account page, and my application destroys the access tokens, the next time the WebView is opened, it is probably still logged in, and even if not, it has the password box already filled.

How can I force WebView to not ask to remember passwords, and to not persist session cookies? If that is not possible, can I delete all its stored state (except maybe the image cache)?

Answer

Cassio Landim picture Cassio Landim · Jun 17, 2011

You can use this to prevent cookies from being stored and clean cookies already stored:

CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookies(callback);
cookieManager.setAcceptCookie(false);

WebView webview = new WebView(this);
WebSettings ws = webview.getSettings();
ws.setSaveFormData(false);
ws.setSavePassword(false); // Not needed for API level 18 or greater (deprecated)