現在、API で 2 種類の認証を使用しています。
- ローカル ユーザー + ローカル パスワード
- DBユーザー+DBパスワード
このために、各タイプのデコレーターを定義したいと思います。例:
@authenticator.local_authentication
また
@authenticator.db_authentication
現在、ローカル認証デコレータの作業バージョンがあります。用に作成したいと思います@authenticator.db_authentication
。Miguel の投稿を参照として使用して、db 認証サポートを追加しています。
この例は現在 で動作し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