Bottle 中的基本身份验证

Basic auth authentication in Bottle

如何在 Bottle 框架中执行基本身份验证?在烧瓶中我曾经:

def check( username, password ):
    # This function is called to check if a username/password combination is valid
    return username == 'nikos' and password == '******'


def authenticate():
    # Sends a 401 response that enables basic auth
    return Response( 'Credentials of a registered user required!', 401, {'WWW-Authenticate': 'Basic realm="User!"'} )

并称为:

auth = request.authorization
if not auth or not counters.check( auth.username, auth.password ):
    return counters.authenticate()

如何在 Bottle 框架中实现相同的功能?

据报道here, Bottle natively contains 使基本身份验证非常简单的装饰器:

from bottle import auth_basic, request, route

def is_authenticated_user(user, password):
    # You write this function. It must return
    # True if user/password is authenticated, or False to deny access.

@route('/')
@auth_basic(is_authenticated_user)
def home():
    return ['hooray, you are authenticated! your info is: {}'.format(request.auth)]

改编自 ron rothman 使用 werkzeug 的基本身份验证解决方案。

from bottle import auth_basic, request, route
from werkzeug.security import generate_password_hash, check_password_hash


users = {'user1': generate_password_hash('pwd!')}


def is_authenticated_user(user, password):
    # You write this function. It must return
    # True if user/password is authenticated, or False to deny access.
    if user in users and check_password_hash(users.get(user), password):
        return True
    else:
        return False


@route('/')
@auth_basic(is_authenticated_user)
def home():
    return ['hooray, you are authenticated! your info is: {}'.format(request.auth)]