跨域预检查的事先请求(Pre-flight Request)会使用OPTIONS方法发送请求,所以在flask中,如果要对请求进行认证,并作为一个装饰器,可以这样写:
def auth_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token_type, token = get_token()
# Flask normally handles OPTIONS requests on its own, but in the
# case it is configured to forward those to the application, we
# need to ignore authentication headers and let the request through
# to avoid unwanted interactions with CORS.
if request.method != 'OPTIONS':
if token_type is None or token_type.lower() != 'bearer':
return api_abort(400, 'The token type must be bearer.')
if token is None:
return token_missing()
if not validate_token(token):
return invalid_token()
return f(*args, **kwargs)
return decorated
如此,在OPTIONS请求方式之外进行对token的验证。
网友评论