我有一组用户角色在Flask-User的网页侧布局和保护。现在我想允许他们对我的API进行REST调用,这些调用将使用@roles_required
进行划分以过滤请求。如何进行REST登录并将令牌\凭证传递给Flask-USER以使@roles_required
生效?
答案 0 :(得分:4)
您必须检查Dillon Dixan的存储库,在那里他提出了一个非常漂亮的示例,它可以帮助您实现查询。以下是示例代码:
from flask import Flask
from flask_basic_roles import BasicRoleAuth
app = Flask(__name__)
auth = BasicRoleAuth()
# Let's add some users.
auth.add_user(user='bob', password='secret123', roles='producer')
auth.add_user(user='alice', password='drowssap', roles=('producer','consumer'))
auth.add_user(user='bill', password='54321')
auth.add_user(user='steve', password='12345', roles='admin')
# Only producers and admins can post, while consumers can only get.
# Admins can also perform all other verbs.
@app.route("/task")
@auth.require(roles={
'POST': 'producer',
'GET': 'consumer',
'DELETE,POST,PATCH,PUT,GET': 'admin'
})
def tasks_endpoint(methods=(...)):
return "Here tasks get produced and consumed!"
# We can secure by user too. Steve can use any verb on this
# endpoint and everyone else is denied access.
@app.route("/task_status")
@auth.require(users='steve')
def task_status_endpoint(methods=(...)):
return "Here are the task statuses!"
# Alice, Bill and users with an 'admin' role can access this, while everyone
# else is denied on all verbs.
@app.route("/task_failures")
@auth.require(users=('alice', 'bill'), roles='admin')
def task_failures(methods=(...)):
return "Here are the task failures!"
# Everyone including unauthenticated users can view task results.
@app.route("/task_results")
def task_results(methods=(...)):
return "Here are the task results!"
if __name__ == "__main__":
app.run()
您需要做的就是使用flask_basic_roles
安装库pip
。
休息,您可以查看示例,当然会帮助您。
此外,您还可以访问并查看:https://github.com/raddevon/flask-permissions
请从这里阅读烧瓶许可:https://pythonhosted.org/Flask-Security/。