【问题标题】:Enable or disable @auth_basic() programmatically以编程方式启用或禁用 @auth_basic()
【发布时间】:2018-08-01 20:51:18
【问题描述】:

我正在尝试在我的程序中使用 Bottle 框架 @auth_basic(check_credentials) 装饰器,但我希望能够根据用户在程序设置中做出的选择来启用或禁用它。

如果设置为False,我尝试在check_credentials 中执行if 以返回True,但我仍然收到始终返回True 的登录弹出窗口。我根本不想弹出窗口。

知道如何实现吗?

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

@route('/')
@auth_basic(check_credentials)
def root():
    # ---page content---

【问题讨论】:

  • 你能解释一下你使用什么框架或展示一些代码吗?
  • 对不起,我只添加了瓶子标签,并没有在文本中提及它。
  • 你试过在检查函数中记录auth_enabled的值吗?
  • 是的,auth_enabled 值很好。将装饰器添加到路由后,就会显示基本的身份验证弹出窗口。我需要在它显示之前拦截它。
  • @morpheus65535 我用自定义 auth_basic 更新了答案

标签: python bottle


【解决方案1】:

HTTP Auth 正在弹出,因为您正在使用来自 Bottle 框架的装饰器,这是默认行为 link

您的设置实际上是始终让所有人进入,而不是禁用 HTTP 弹出窗口。您需要做的是实现另一个检查密码的“中间件”。

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 2013-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    相关资源
    最近更新 更多