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

2024-04-23 11:54:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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


Tags: selfauth身份验证路由defcheckusernamepassword
3条回答

您可以利用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()

如果您尝试使用自定义的端点身份验证,则会发现很难做到如下所述: https://github.com/pyeve/eve/issues/860 我最后编写了一个包装器来解决“resource”没有传递给“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

这样,您可以在域中定义身份验证类:

^{pr2}$

在我的应用程序中,我包装了requires\u auth decorator,并将其添加为身份验证资源。在

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

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

如果您使用flask blueprints来定制路线,那么可以为blueprint添加一个before request函数。在

首先,创建一个函数来检查蓝图中的身份验证。您需要自己从flask请求中获取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'

然后,可以将此函数设置为在每个blueprint请求之前调用。下面是一个blueprint定义的示例,设置before_request函数:

^{pr2}$

最后,您需要将蓝图与您的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()

希望有帮助。在

相关问题 更多 >