代码如下:
from flask import request, g, make_response
from flask_httpauth import HTTPBasicAuth
from flask_restful import abort
from api.test.a_module import a_module
from api.test.b_module import b_module
# 认证
BASIC_ISR_AUTH_DICT = {
#身份验证信息
'caller': 'btest'
}
isr_auth = HTTPBasicAuth()
@isr_auth.get_password
def get_pwd(username):
try:
if username in BASIC_ISR_AUTH_DICT:
return BASIC_ISR_AUTH_DICT.get(username)
else:
abort(401)
except Exception as ex:
abort(401)
def basic_required(auther, role=None, optional=None):
auth = auther.get_auth()
# 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': # pragma: no cover
password = auther.get_auth_password(auth)
status = None
user = auther.authenticate(auth, password)
if user in (False, None):
status = 401
elif not auther.authorize(role, user, auth):
status = 403
if not optional and status:
try:
return auther.auth_error_callback(status)
except TypeError:
return auther.auth_error_callback()
g.flask_httpauth_user = user if user is not True \
else auth.username if auth else None
res = make_response()
res.status_code = 200
return res
def make_http_res(data, code):
rst = make_response(data)
return rst, code
@app.before_request
def auth_before():
try:
if request.blueprint == 'flasgger':
if os.environ.get("FLASK_ENV", '').lower() not in ['dev', 'development', 'test']:
abort(401)
# 蓝本
if request.blueprint in [a_module.name, b_module.name]:
res = basic_required(isr_auth)
if res.status_code == 401:
return res
except Exception as e:
code = e.code if hasattr(e, 'code') else 500
return make_http_res('auth server:' + str(e), code)