【问题标题】:python-eve tokenauth 401 errorpython-eve tokenauth 401 错误
【发布时间】:2014-10-08 10:07:24
【问题描述】:

Settings.py:

RESOURCE_METHODS = ['GET', 'POST', 'DELETE']

ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE']

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

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

DOMAIN = {
    'accounts': accounts,
}

运行.py:

from eve import Eve
from eve.auth import TokenAuth
import random
import string


class RolesAuth(TokenAuth):
     def check_auth(self, token, allowed_roles, resource, method):
         # use Eve's own db driver; no additional connections/resources are used
         accounts = app.data.driver.db['accounts']
         lookup = {'token': token}
         if allowed_roles:
             #only retrieve a user if his roles match ``allowed_roles``
             lookup['roles'] = {'$in': allowed_roles}
         account = accounts.find_one(lookup)
         return account


def add_token(documents):
     # Don't use this in production:
     # You should at least make sure that the token is unique.
     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_accounts += add_token
     app.run()

mongodb(账户集合):

db.accounts.find({username:"prova"})
{ "_id" : ObjectId("num"), "username" : "prova", "password" : "prova", "roles" : "admin", "token" : "blabla" }

cmd(cHJvdmE6YmxhYmxhprova:blabla):

curl -X GET "http://localhost:5000/accounts" -H "Content-Type: application/json" -H "Authorization: Basic cHJvdmE6YmxhYmxh"

我的问题是我收到一个 401 错误,告诉我身份验证错误。
我还尝试了仅使用 base64 编码的令牌,但没有任何改变。有什么想法吗?
我正在使用 Eve-0.4 和 Eve-0.5。

【问题讨论】:

    标签: python mongodb flask eve


    【解决方案1】:

    使用令牌身份验证,您只需将实际令牌与您的请求一起传递:没有用户名,没有密码。在测试您的代码时,我可以看到token 的值是prova,而您想要的是blabla(这是实际的令牌值)。

    您可以通过在check_auth 中添加pdb 断点来验证自己。因此,请尝试将 YmxhYmxhOg== (blabla) 与您的 Auth 请求标头一起使用。

    【讨论】:

      猜你喜欢
      • 2014-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      • 1970-01-01
      • 2018-06-12
      • 2016-06-04
      • 2019-05-19
      相关资源
      最近更新 更多