Flask身份验证装饰器

时间:2017-10-31 08:37:47

标签: python flask flask-login flask-httpauth

目前,我在我的API中使用了两种类型的身份验证:

  • 本地用户+本地密码
  • 数据库用户+数据库密码

为此,我想为每种类型定义一个装饰器。例如:

@authenticator.local_authentication

@authenticator.db_authentication

目前我有本地身份验证装饰器的工作版本。 我想为@authenticator.db_authentication创建一个。我使用Miguel的post作为参考来添加数据库身份验证支持。

该示例目前适用于HTTPBasicAuth

在使用:auth.login_required处理身份验证时,我需要覆盖需要定义的auth.verify_password@auth.login_required

理想情况下,我想在我的API方法中定义类似的内容:

@authenticator.db_authentication
def get(self):
 ...

这是需要修改的工作代码:

from flask_httpauth import HTTPBasicAuth
auth = HTTPBasicAuth()

@auth.verify_password
def verify_password(username_or_token, password):
    """Validates username or password in database.

    :param username_or_token:
    :param password:
    :return: user
    """
    return authenticator.db_authentication(username_or_token, password)

class Status(Resource):
    """Used for verifying API status"""

    @auth.login_required
    def get(self):
        """

        :return:
        """
        log.info(request.remote_addr + ' ' + request.__repr__())
        log.info('api() | GET | Received request for Status')
        response = json.dumps('Status: Hello %s!' % g.user.username)
        return Response(response, status=200, mimetype=settings.api_mime_type)

    @authenticator.local_authentication
    def post(self):
        log.info(request.remote_addr + ' ' + request.__repr__())
        log.info('api() | POST | Received request for Status')
        response = json.dumps('Status: POST. %s' % settings.api_ok)
        return Response(response, status=202, mimetype=settings.api_mime_type)

我想将@auth.login_required更改为@authenticator.db_authentication

以下不同文件中@authenticator.local_authentication的示例:

def check_auth(username, password):
    """ Basic authentication: local username and password.

    :param username:
    :param password:
    :return:
    """
    return username == settings.api_account and password == settings.api_password


def authentication_error():
    """
    Authentication error.
    :return:
    """

    response = jsonify({'message': "Authenticate."})
    response.headers['WWW-Authenticate'] = settings.api_realm
    response.status_code = 401
    return response


def local_authentication(f):
    """Decorator to check local authentication.
    :param f: A function
    :return: itself: Decorator check_credentials
    """

    @wraps(f)
    def check_credentials(*args, **kwargs):
        auth = request.authorization
        if not auth:
            return authentication_error()

        elif not check_auth(auth.username, auth.password):
            return authentication_error()
        return f(*args, **kwargs)

    return check_credentials

def db_authentication(username_or_token, password):
    """First try to authenticate by token.

    :param username_or_token:
    :param password:
    :return: boolean
    """

    user = Model.ApiUsers.verify_auth_token(username_or_token)
    if not user:
        # Try to authenticate with database password.
        user = Model.ApiUsers.query.filter_by(username=username_or_token).first()
        if not user or not user.verify_password(password):
            return False
    g.user = user
    return True

0 个答案:

没有答案