目前我在我的 API 中使用两种类型的身份验证:
- 本地用户+本地密码
- 数据库用户+数据库密码
为此,我想为每种类型定义一个装饰器。例子:
@authenticator.local_authentication
或者
@authenticator.db_authentication
目前我有一个本地身份验证装饰器的工作版本。我想为@authenticator.db_authentication
. 我使用 Miguel 的帖子作为添加数据库身份验证支持的参考。
该示例当前适用于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