且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

以编程方式启用或禁用@auth_basic()

更新时间:2023-02-13 10:13:21

HTTP身份验证正在弹出,因为您正在使用Bottle框架中的装饰器,这是默认行为链接

HTTP Auth is popping because you are using the decorator from the bottle framework and this is a default behavior link.

您的设置实际上总是在做让所有人都参与进来,而不是禁用HTTP弹出窗口。您需要做的是实现另一个中间件来检查密码。

What your setting actually do is always letting everyone in, not to disable the HTTP pop up. What you need to do is to implement another "middleware" that checks for the password.

from bottle import route, Response, run, HTTPError, request

auth_enabled = True


def custom_auth_basic(check, realm="private", text="Access denied"):
    ''' Callback decorator to require HTTP auth (basic).
        TODO: Add route(check_auth=...) parameter. '''
    def decorator(func):
        def wrapper(*a, **ka):
            if auth_enabled:
                user, password = request.auth or (None, None)
                if user is None or not check(user, password):
                    err = HTTPError(401, text)
                    err.add_header('WWW-Authenticate', 'Basic realm="%s"' % realm)
                    return err
                return func(*a, **ka)
            else:
                return func(*a, **ka)

        return wrapper
    return decorator


def check_credentials(user, pw):
    if auth_enabled:
        username = "test"
        password = "test"
        if pw == password and user == username:
            return True
        return False
    else:
        return True


@route('/')
@custom_auth_basic(check_credentials)
def root():
    return Response("Test")


run(host='localhost', port=8080)