Basic auth authentication in Bottle

时间:2018-09-22 23:01:31

标签: python bottle

How can i perform basic authentication in bottle framework? in flask i used to:

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!"'} )

and called as:

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

How can i achieve the same in Bottle framework?

2 个答案:

答案 0 :(得分:1)

据报告here,瓶子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)]

答案 1 :(得分:0)

改编自 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)]