【问题标题】:Issue with the Python Eve TokenAuth FeaturePython Eve TokenAuth 功能的问题
【发布时间】:2014-08-19 18:44:07
【问题描述】:

几天以来,我一直在测试 python-eve 库以创建一个宁静的 API,但是当我按照 tutorial 实现“令牌身份验证”时遇到了一些问题。

这是我的用户架构:

users_schema = {
    'username': {
         'type': 'string',
         'required': True,
         'unique': True,
         },
     'password': {
         'type': 'string',
         'required': True,
     },
     'roles': {
         'type': 'list',
         'allowed': ['user', 'sudo', 'admin'],
         'required': True,
     },
     'token': {
         'type': 'string',
         'required': True,
     }
 }

这是我的用户域配置:

users = {
    'title': 'user',
    'additional_lookup': {
        'url': 'regex("[\w]+")',
        'field': 'username'
    },
    'cache_control': '',
    'cache_expires': 0,
    'allowed_roles': ['sudo', 'admin', 'user'],
    'extra_response_fields': ['token'],
    'schema': users_schema
}

这是我运行来测试我的 API 的代码:

class RolesAuth(TokenAuth):
    def check_auth(self, token,  allowed_roles, resource, method):
        users = app.data.driver.db['users']
        lookup = {'token': token}
        if allowed_roles:
            lookup['roles'] = {'$in': allowed_roles}
        user = users.find_one(lookup)
        return user

    def add_token(documents):
        for document in documents:
            document["token"] = (''.join(random.choice(string.ascii_uppercase) for x in range(10)))

if __name__ == '__main__':
    app = Eve(auth=RolesAuth)
    app.on_insert_users += add_token
    app.run()

我的问题是当我尝试像这样在用户端点上发出请求时

curl -X GET "http://localhost:5000/users" -H "Content-Type: application/json" -H "Authorization: Basic <MY_TOKEN>"

作为实际存储在用户集合中的令牌,我总是收到以下错误:

请提供正确的凭据

在 API 日志中:

127.0.0.1 - [29/Jun/2014 03:12:32] “GET /users HTTP/1.1”401 -

这是我在 mongodb 中用于此示例的用户令牌的示例:

{
    "username" : "cmorent",
    "password" : "<MY_PASSWORD>"
    "roles" : [
        "sudo",
        "admin",
        "user"
    ],
    "token" : "<MY_TOKEN>"
}

你们知道我做错了什么吗?这是我发送的授权标头有问题吗?

谢谢大家的帮助!

【问题讨论】:

    标签: python mongodb flask eve


    【解决方案1】:

    您是否正确编码了随请求发送的令牌? Basic/Token auth 需要 Base64 编码。我建议您尝试使用某种客户端(例如 Chrome 中的 Postman),这样您就可以看到实际发生的情况以及身份验证令牌的编码方式。

    【讨论】:

    • 事实上,我没有对它进行 base 64 编码...谢谢 Nicola!
    • 刚刚尝试过,但我仍然收到“请提供适当的信用证”信息。我试图在我的 check_auth 方法中添加一些调试,当我尝试 POST/GET 某些东西时,它什么也没打印。你觉得里面有什么不对吗?
    • 好吧,我的错,我现在一切正常。再次非常感谢 Nicola!
    • @NicolaIarocci 我偶然发现了同样的问题。请参阅此 SO 帖子。关于我在这里做错了什么的任何想法。很确定令牌是 Base64 编码的。
    • 这里是缺少的链接:stackoverflow.com/questions/27501022/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    相关资源
    最近更新 更多