Dan*_*B91 0 python rest restful-authentication flask flask-restful
我对RESTful API比较新,所以我当然不能正确设计它.
我想根据正在进行身份验证的人从/ api/users/[user_id]返回JSON用户对象的不同子集.因此,如果用户"alice"试图访问/ api/users/alice,她将获得更多她的信息(例如私人设置等),而不是用户"bob",她只是简单地获取她的公开个人资料.
我目前正在使用flask_restful和httpbasicauth.现在我有以下内容:
class UserAPI(flask_restful.Resource):
@g.auth.login_required
def get(self, username):
# here is where I want to get the HTTPBasicAuth username
# to determine how much data to return
user = User.objects(username=username).exclude('password').first()
if user is not None:
return user.to_json()
else:
flask_restful.abort(404, message='User not found: ' + username)
Run Code Online (Sandbox Code Playgroud)
问题是我似乎无法找到一种清晰的方法来获取HTTP基本身份验证数据.我知道我可以解析请求并解码base-64数据,但我觉得我不应该这样做.或者,更好的是,找到一种方法将user_id从/ api/users/[user_id]传递到login_required注释中.
我觉得这将是一个非常常见的用例,所以我无法弄清楚为什么我在这个领域找不到任何东西.我设计这个完全错了吗?
非常感谢!
我建议不要使用flask.ext.httpauth.我觉得它没有用.我使用一个装饰器,它接受Authorization标头并用db检查它.您可以访问在request.authorization.username中输入的用户名,密码在request.authorization.password中.
from flask import request
from flask.ext.restful import abort, Resource
from functools import wraps
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth:
abort(401)
user = User.objects(username=auth.username).first()
auth_ok = False
if user != None:
auth_ok = verify_password(auth.password) == user.password
if not auth_ok:
return abort(401)
return f(*args, **kwargs)
return decorated
class UserAPI(Resource):
@requires_auth
def get(self):
user = User.objects(username=request.authorization.username).\
exclude('password').first()
if user is not None:
return user.to_json()
else:
abort(404, message='User not found: ' + username)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1847 次 |
| 最近记录: |