HttpAuth是什么
- HttpAuth是比較早的http的驗(yàn)證的一個方案
- 認(rèn)證過程通過http協(xié)議來完成
WebView如何支持
- HttpAuth本身是Http協(xié)議來支持挺份,在Http的頭有標(biāo)記
- WebView會有回調(diào)來方便客戶端自己來自定義實(shí)現(xiàn)彈出框
- WebView的內(nèi)部類WebViewClient中的回調(diào)方法onReceivedHttpAuthRequest
WebView端實(shí)現(xiàn)
- 實(shí)現(xiàn)1裹粤,從url中根據(jù)規(guī)則獲取用戶名密碼袱贮,自動填充卓舵,進(jìn)行驗(yàn)證
- url中沒有用戶名密碼睦疫,實(shí)現(xiàn)彈窗,用戶輸入用戶名密碼后透绩,根據(jù)填充內(nèi)容進(jìn)行驗(yàn)證
@Override
public void onReceivedHttpAuthRequest(WebView view,
final HttpAuthHandler handler, final String host,
final String realm) {
String username = null;
String password = null;
boolean reuseHttpAuthUsernamePassword = handler
.useHttpAuthUsernamePassword();
if (reuseHttpAuthUsernamePassword && view != null) {
String[] credentials = view.getHttpAuthUsernamePassword(host,
realm);
if (credentials != null && credentials.length == 2) {
username = credentials[0];
password = credentials[1];
}
}
if (username != null && password != null) {
handler.proceed(username, password);
} else {
if (isActive()) {
showHttpAuthentication(handler, host, realm, null, null,
null, 0);
} else {
handler.cancel();
}
}
}
httpAuth測試代碼實(shí)現(xiàn)
- 使用flask完成最小httpauth原型
- 使用定義好的webview訪問flask完成實(shí)現(xiàn)
- 參考httpAuth實(shí)現(xiàn)片段
- 瀏覽器上訪問http://127.0.0.1:5000 可以彈出對話框說明實(shí)現(xiàn)完畢
#!/usr/bin/env python
# coding: utf-8
from functools import wraps
from flask import request, Response, Flask
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
return username == 'admin' and password == 'secret'
def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
app = Flask(__name__)
@app.route('/secret-page')
@requires_auth
def secret_page():
return 'secret_page'
if __name__ == '__main__':
app.run(host="0.0.0.0",debug=True)