【问题标题】:Flask RESTful API and authenticating for a specific userFlask RESTful API 和特定用户的身份验证
【发布时间】:2015-11-24 06:20:14
【问题描述】:

我对 RESTful API 比较陌生,所以我当然可能没有正确设计它。

我想根据身份验证者从 /api/users/[user_id] 返回 JSON 用户对象的不同子集。因此,如果用户“alice”试图访问 /api/users/alice,她将获得比用户“bob”更多的信息(例如私人设置等),用户“bob”只会获得她的公开资料。

我目前正在使用带有 httpbasicauth 的 flask_restful。现在我有以下内容:

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) 

问题是我似乎无法找到一种干净的方式来获取 HTTP 基本身份验证数据。我知道我可以解析请求并解码 base-64 数据,但我觉得我不应该这样做。或者,更好的是,找到一种方法将 /api/users/[user_id] 中的 user_id 传递到 login_required 注释中。

我觉得这将是一个非常常见的用例,所以我无法弄清楚为什么我在这个领域找不到任何东西。我的设计完全错了吗?

非常感谢!

【问题讨论】:

    标签: python rest flask restful-authentication flask-restful


    【解决方案1】:

    我建议不要使用 flask.ext.httpauth。我没有发现它很有用。我使用了一个装饰器,它接受 Authorization 标头并使用 db.xml 进行检查。您可以访问在 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)
    

    【讨论】:

    • 非常感谢!不知道 request.authorization 字段:/
    猜你喜欢
    • 1970-01-01
    • 2011-11-28
    • 2016-03-15
    • 1970-01-01
    • 2015-06-06
    • 1970-01-01
    • 2020-01-26
    • 2013-08-21
    • 2011-10-02
    相关资源
    最近更新 更多