Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Webview auto login to https website by setting token cookie

What I am trying to achieve is to autologin to a https website by setting a token as a cookie.

( It works on android chrome browser but not in application webview )

Basically I am facing two issue while loading https url into web view with cookie set

Issue 1

I am getting following log message.

Failed to validate the certificate chain, error: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

I tried overriding onReceivedSslError and called handler.proceed(); as below.

@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
    Log.d(TAG, "==> " + error.toString());
    handler.proceed();
}

But still I see white page ( I am assuming Its happening because of certificate issue. )

Issue 2

I have got a login url with me ( e.g https://www.abc.com/login.html )

What I am trying to achieve is auto login into web view by setting a cookie.

CookieSyncManager.createInstance(webView.getContext());
CookieManager cookieManager = CookieManager.getInstance();
CookieManager.getInstance().setAcceptCookie(true);

String token = PreferenceHelper.loadTokenFromPreference(this);

String sessionCookie = "staging=" + token;

cookieManager.setCookie("https://www.abc.com/aaa/",
    sessionCookie);
CookieSyncManager.getInstance().sync();

SystemClock.sleep(1000);

But still I am not able to auto login.Rather I am seeing the white page.

What I am not sure now is exactly where I am making a mistake.

cookieManager.setCookie requires first argument as a url for which cookie needs to set,I am not sure exactly which url i need to give it ?

Can anyone suggest me the right approach to get it working ?

Thanks

like image 945
Vipul Avatar asked Sep 12 '14 09:09

Vipul


1 Answers

You can pass the Cookie as HttpHeader in loadUrl function of WebView.

HashMap<String, String> map = new HashMap<String, String>();
String token = PreferenceHelper.loadTokenFromPreference(this);
String sessionCookie = "staging=" + token;
map.put("Cookie", sessionCookie);
webView.loadUrl(url, map);
like image 101
Abhishek V Avatar answered Nov 15 '22 00:11

Abhishek V