如何使用BasicAuth保护自定义端点?

时间:2016-07-02 12:44:25

标签: python eve

假设我已使用BasicAuth启用了对资源的身份验证:

class MyBasicAuth(BasicAuth):
    def check_auth(self,username,password,allowed_roles,resource,method):
        return username == 'secretusername' and password == 'secretpass'

我还有自定义路由,用于从HTML视图管理文档。如何使用相同的MyBasicAuth保护所有自定义路由?我还需要实现使用上面的MyBasicAuth进行身份验证的逻辑。 请帮我解决一下这个。它是供个人使用的,所以我更喜欢硬编码用户名和密码。

3 个答案:

答案 0 :(得分:2)

您可以利用Eve本身内部使用的requires_auth装饰器。这样,您的auth类也将用于保护您的自定义路线:

from eve import Eve
from eve.auth import requires_auth

app = Eve()

@app.route('/hello')
@requires_auth('resource')
def hello_world():
    return 'Hello World!'


if __name__ == '__main__':
    app.run()

答案 1 :(得分:2)

如果您尝试使用自定义端点身份验证,则会发现此处提到的内容很困难: https://github.com/pyeve/eve/issues/860 我最后写了一个包装器,以解决'资源'没有被传递给'requires_auth'的问题:

def auth_resource(resource):
def fdec(f):
    @wraps(f)
    def wrapped(*args, **kwargs):
            return f(resource=resource, *args, **kwargs)
    return wrapped
return fdec

这样您就可以在DOMAIN中定义一个身份验证类:

DOMAIN = {
    'testendpoint'= {'authentication':MyCustomAuthetication},
    'otherendpoints'=...

在我的应用程序中,我已经包装了requires_auth装饰器并将其添加为身份验证资源。

@app.route('/testendpoint/<item>', methods=['GET'])
@auth_resource('testendpoint')
@requires_auth('item')
def my_end_point_function(*args, **kwargs):
    dosomthinghere

只要在端点的设置文件中定义了身份验证类,这也允许您重用在另一个端点中定义的任何身份验证,如果您想确保所有端点使用相同的身份验证,这可能很方便。 / p>

答案 2 :(得分:0)

如果您正在为自定义路线使用烧瓶蓝图,则可以为您的蓝图添加先请求功能。

首先,创建一个从蓝图检查身份验证的功能。您需要自己从烧瓶请求中获取Authorization标头,如下所示:

from flask import request, abort, current_app
from werkzeug.http import parse_authorization_header

def check_blueprint_auth():
    if 'Authorization' not in request.headers:
        print('Authorization header not found for authentication')
        return abort(401, 'Authorization header not found for authentication')
    header = parse_authorization_header(request.headers['Authorization'])
    username = None if header is None else header['username']
    password = None if header is None else header['password']

    return username == 'secretusername' and password == 'secretpass'

然后,您可以在每个蓝图的请求之前设置此函数。下面是蓝图定义的示例,设置before_request函数:

from flask import Blueprint, current_app as app
# your auth function
from auth import check_blueprint_auth

blueprint = Blueprint('prefix_uri', __name__)

# this sets the auth function to be called
blueprint.before_request(check_blueprint_auth)


@blueprint.route('/custom_route/<some_value>', methods=['POST'])
def post_something(some_value):
#  something

最后,您需要将蓝图与eve应用绑定。关于如何绑定蓝图的示例,部分来自here

from eve import Eve
# your blueprint
from users import blueprint
from flask import current_app, request

app = Eve()
# register the blueprint to the main Eve application
app.register_blueprint(blueprint)

app.run()

希望有所帮助。

相关问题