Flask auth_before中使用统一basic认证

代码如下:

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值