Reputation:
I'm building an API with Flask-Restless that requires an API key, that will be in the Authorization
HTTP header.
In the Flask-Restless example here for a preprocessor:
def check_auth(instance_id=None, **kw):
# Here, get the current user from the session.
current_user = ...
# Next, check if the user is authorized to modify the specified
# instance of the model.
if not is_authorized_to_modify(current_user, instance_id):
raise ProcessingException(message='Not Authorized',
status_code=401)
manager.create_api(Person, preprocessors=dict(GET_SINGLE=[check_auth]))
How do I retrieve the Authorization
header in the check_auth
function?
I have tried accessing the Flask response
object, but it is None
during the scope of this function. The kw
parameter is also an empty dict.
Upvotes: 2
Views: 2180
Reputation: 1121486
In a normal Flask request-response cycle, the request
context is active when the Flask-Restful preprocessors and postprocessors are being run.
As such, using:
from flask import request, abort
def check_auth(instance_id=None, **kw):
current_user = None
auth = request.headers.get('Authorization', '').lower()
try:
type_, apikey = auth.split(None, 1)
if type_ != 'your_api_scheme':
# invalid Authorization scheme
ProcessingException(message='Not Authorized',
status_code=401)
current_user = user_for_apikey[apikey]
except (ValueError, KeyError):
# split failures or API key not valid
ProcessingException(message='Not Authorized',
status_code=401)
should Just Work.
Upvotes: 6