首页 > 解决方案 > 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()

我怎样才能在瓶子框架中实现同样的目标?

标签: pythonbottle

解决方案


正如这里所报道的,Bottle本身包含一个装饰器,使 Basic Auth 非常简单:

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)]

推荐阅读