Android经验分享

Android Webview中支持HttpAuth

2019-02-14  本文已影响0人  没头脑和挺高兴

HttpAuth是什么

WebView如何支持

WebView端实现

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

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


上一篇下一篇

猜你喜欢

热点阅读