83f70ac93af0505a1c3bc891882003a74dcbf276
[pub/Android/ownCloud.git] / src / com / owncloud / android / authentication / SsoWebViewClient.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 ownCloud Inc.
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2,
6 * as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 */
17
18 package com.owncloud.android.authentication;
19
20 import java.io.ByteArrayInputStream;
21 import java.lang.ref.WeakReference;
22 import java.security.cert.Certificate;
23 import java.security.cert.CertificateException;
24 import java.security.cert.CertificateFactory;
25 import java.security.cert.X509Certificate;
26
27 import android.app.AlertDialog;
28 import android.app.AlertDialog.Builder;
29 import android.content.Context;
30 import android.content.DialogInterface;
31 import android.graphics.Bitmap;
32 import android.net.http.SslCertificate;
33 import android.net.http.SslError;
34 import android.os.Bundle;
35 import android.os.Handler;
36 import android.os.Message;
37 import android.text.InputType;
38 import android.view.KeyEvent;
39 import android.view.View;
40 import android.webkit.CookieManager;
41 import android.webkit.HttpAuthHandler;
42 import android.webkit.SslErrorHandler;
43 import android.webkit.WebResourceResponse;
44 import android.webkit.WebView;
45 import android.webkit.WebViewClient;
46 import android.widget.EditText;
47 import android.widget.LinearLayout;
48
49 import com.owncloud.android.R;
50 import com.owncloud.android.lib.common.network.NetworkUtils;
51 import com.owncloud.android.utils.Log_OC;
52
53
54 /**
55 * Custom {@link WebViewClient} client aimed to catch the end of a single-sign-on process
56 * running in the {@link WebView} that is attached to.
57 *
58 * Assumes that the single-sign-on is kept thanks to a cookie set at the end of the
59 * authentication process.
60 *
61 * @author David A. Velasco
62 */
63 public class SsoWebViewClient extends WebViewClient {
64
65 private static final String TAG = SsoWebViewClient.class.getSimpleName();
66
67 public interface SsoWebViewClientListener {
68 public void onSsoFinished(String sessionCookie);
69 }
70
71 private Context mContext;
72 private Handler mListenerHandler;
73 private WeakReference<SsoWebViewClientListener> mListenerRef;
74 private String mTargetUrl;
75 private String mLastReloadedUrlAtError;
76
77 public SsoWebViewClient (Context context, Handler listenerHandler, SsoWebViewClientListener listener) {
78 mContext = context;
79 mListenerHandler = listenerHandler;
80 mListenerRef = new WeakReference<SsoWebViewClient.SsoWebViewClientListener>(listener);
81 mTargetUrl = "fake://url.to.be.set";
82 mLastReloadedUrlAtError = null;
83 }
84
85 public String getTargetUrl() {
86 return mTargetUrl;
87 }
88
89 public void setTargetUrl(String targetUrl) {
90 mTargetUrl = targetUrl;
91 }
92
93 @Override
94 public void onPageStarted (WebView view, String url, Bitmap favicon) {
95 Log_OC.d(TAG, "onPageStarted : " + url);
96 super.onPageStarted(view, url, favicon);
97 }
98
99 @Override
100 public void onFormResubmission (WebView view, Message dontResend, Message resend) {
101 Log_OC.d(TAG, "onFormResubMission ");
102
103 // necessary to grant reload of last page when device orientation is changed after sending a form
104 resend.sendToTarget();
105 }
106
107 @Override
108 public boolean shouldOverrideUrlLoading(WebView view, String url) {
109 return false;
110 }
111
112 @Override
113 public void onReceivedError (WebView view, int errorCode, String description, String failingUrl) {
114 Log_OC.e(TAG, "onReceivedError : " + failingUrl + ", code " + errorCode + ", description: " + description);
115 if (!failingUrl.equals(mLastReloadedUrlAtError)) {
116 view.reload();
117 mLastReloadedUrlAtError = failingUrl;
118 } else {
119 mLastReloadedUrlAtError = null;
120 super.onReceivedError(view, errorCode, description, failingUrl);
121 }
122 }
123
124 @Override
125 public void onPageFinished (WebView view, String url) {
126 Log_OC.d(TAG, "onPageFinished : " + url);
127 mLastReloadedUrlAtError = null;
128 if (url.startsWith(mTargetUrl)) {
129 view.setVisibility(View.GONE);
130 CookieManager cookieManager = CookieManager.getInstance();
131 final String cookies = cookieManager.getCookie(url);
132 Log_OC.d(TAG, "Cookies: " + cookies);
133 if (mListenerHandler != null && mListenerRef != null) {
134 // this is good idea because onPageFinished is not running in the UI thread
135 mListenerHandler.post(new Runnable() {
136 @Override
137 public void run() {
138 SsoWebViewClientListener listener = mListenerRef.get();
139 if (listener != null) {
140 // Send Cookies to the listener
141 listener.onSsoFinished(cookies);
142 }
143 }
144 });
145 }
146 }
147 }
148
149
150 @Override
151 public void doUpdateVisitedHistory (WebView view, String url, boolean isReload) {
152 Log_OC.d(TAG, "doUpdateVisitedHistory : " + url);
153 }
154
155 @Override
156 public void onReceivedSslError (final WebView view, final SslErrorHandler handler, SslError error) {
157 Log_OC.d(TAG, "onReceivedSslError : " + error);
158 // Test 1
159 X509Certificate x509Certificate = getX509CertificateFromError(error);
160 boolean isKnownServer = false;
161
162 if (x509Certificate != null) {
163 Log_OC.d(TAG, "------>>>>> x509Certificate " + x509Certificate.toString());
164
165 try {
166 isKnownServer = NetworkUtils.isCertInKnownServersStore((Certificate) x509Certificate, mContext);
167 } catch (Exception e) {
168 Log_OC.e(TAG, "Exception: " + e.getMessage());
169 }
170 }
171
172 if (isKnownServer) {
173 handler.proceed();
174 } else {
175 ((AuthenticatorActivity)mContext).showUntrustedCertDialog(x509Certificate, error, handler);
176 }
177 }
178
179 /**
180 * Obtain the X509Certificate from SslError
181 * @param error SslError
182 * @return X509Certificate from error
183 */
184 public X509Certificate getX509CertificateFromError (SslError error) {
185 Bundle bundle = SslCertificate.saveState(error.getCertificate());
186 X509Certificate x509Certificate;
187 byte[] bytes = bundle.getByteArray("x509-certificate");
188 if (bytes == null) {
189 x509Certificate = null;
190 } else {
191 try {
192 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
193 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
194 x509Certificate = (X509Certificate) cert;
195 } catch (CertificateException e) {
196 x509Certificate = null;
197 }
198 }
199 return x509Certificate;
200 }
201
202 @Override
203 public void onReceivedHttpAuthRequest (WebView view, HttpAuthHandler handler, String host, String realm) {
204 Log_OC.d(TAG, "onReceivedHttpAuthRequest : " + host);
205 // Toast.makeText(mContext, "onReceivedHttpAuthRequest : " + host, Toast.LENGTH_LONG).show();
206
207 createAuthenticationDialog(view, handler);
208
209 }
210
211 @Override
212 public WebResourceResponse shouldInterceptRequest (WebView view, String url) {
213 Log_OC.d(TAG, "shouldInterceptRequest : " + url);
214 return null;
215 }
216
217 @Override
218 public void onLoadResource (WebView view, String url) {
219 Log_OC.d(TAG, "onLoadResource : " + url);
220 }
221
222 @Override
223 public void onReceivedLoginRequest (WebView view, String realm, String account, String args) {
224 Log_OC.d(TAG, "onReceivedLoginRequest : " + realm + ", " + account + ", " + args);
225 }
226
227 @Override
228 public void onScaleChanged (WebView view, float oldScale, float newScale) {
229 Log_OC.d(TAG, "onScaleChanged : " + oldScale + " -> " + newScale);
230 super.onScaleChanged(view, oldScale, newScale);
231 }
232
233 @Override
234 public void onUnhandledKeyEvent (WebView view, KeyEvent event) {
235 Log_OC.d(TAG, "onUnhandledKeyEvent : " + event);
236 }
237
238 @Override
239 public boolean shouldOverrideKeyEvent (WebView view, KeyEvent event) {
240 Log_OC.d(TAG, "shouldOverrideKeyEvent : " + event);
241 return false;
242 }
243
244 /**
245 * Create dialog for request authentication to the user
246 * @param webView
247 * @param handler
248 */
249 private void createAuthenticationDialog(WebView webView, HttpAuthHandler handler) {
250 final WebView mWebView = webView;
251 final HttpAuthHandler mHandler = handler;
252
253 // Create field for username
254 final EditText usernameET = new EditText(mContext);
255 usernameET.setHint(mContext.getText(R.string.auth_username));
256
257 // Create field for password
258 final EditText passwordET = new EditText(mContext);
259 passwordET.setHint(mContext.getText(R.string.auth_password));
260 passwordET.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
261
262 // Prepare LinearLayout for dialog
263 LinearLayout ll = new LinearLayout(mContext);
264 ll.setOrientation(LinearLayout.VERTICAL);
265 ll.addView(usernameET);
266 ll.addView(passwordET);
267
268 Builder authDialog = new AlertDialog
269 .Builder(mContext)
270 .setTitle(mContext.getText(R.string.saml_authentication_required_text))
271 .setView(ll)
272 .setCancelable(false)
273 .setPositiveButton(mContext.getText(R.string.common_ok),
274 new DialogInterface.OnClickListener() {
275 public void onClick(DialogInterface dialog, int whichButton) {
276
277 String username = usernameET.getText().toString().trim();
278 String password = passwordET.getText().toString().trim();
279
280 // Proceed with the authentication
281 mHandler.proceed(username, password);
282 dialog.dismiss();
283 }
284 })
285 .setNegativeButton(mContext.getText(R.string.common_cancel),
286 new DialogInterface.OnClickListener() {
287 public void onClick(DialogInterface dialog, int whichButton) {
288 dialog.dismiss();
289 mWebView.stopLoading();
290 }
291 });
292
293 if (mWebView!=null) {
294 authDialog.show();
295 }
296
297 }
298 }