android auth认证,Android Webview中支持HttpAuth

HttpAuth是什么

HttpAuth是比较早的http的验证的一个方案

认证过程通过http协议来完成

WebView如何支持

HttpAuth本身是Http协议来支持,在Http的头有标记

WebView会有回调来方便客户端自己来自定义实现弹出框

WebView的内部类WebViewClient中的回调方法onReceivedHttpAuthRequest

WebView端实现

实现1,从url中根据规则获取用户名密码,自动填充,进行验证

url中没有用户名密码,实现弹窗,用户输入用户名密码后,根据填充内容进行验证

@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测试代码实现

使用flask完成最小httpauth原型

使用定义好的webview访问flask完成实现

浏览器上访问http://127.0.0.1:5000 可以弹出对话框说明实现完毕

#!/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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值