gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:10:52 24 4
gpt4 key购买 nike

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

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

我还有自定义路由,用于从 HTML View 管理文档。如何使用相同的 MyBasicAuth 来保护所有自定义路由?我还需要实现使用上述 MyBasicAuth 进行身份验证的逻辑。请在这件事上给予我帮助。它供个人使用,因此我更喜欢对用户名和密码进行硬编码。

最佳答案

如果您尝试使用自定义端点身份验证,您会发现这里提到的很困难: 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 = {
'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

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

关于python - 如何使用 BasicAuth 保护自定义端点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38160290/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com