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,
}
run.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(cHJvdmE6YmxhYmxh
为prova:blabla
):
curl -X GET "http://localhost:5000/accounts" -H "Content-Type: application/json" -H "Authorization: Basic cHJvdmE6YmxhYmxh"
我的问题是我收到401错误,告诉我auth是错误的。
我也尝试过只使用base64编码的令牌,但没有任何改变。任何想法?
我使用Eve-0.4和Eve-0.5。
答案 0 :(得分:1)
使用令牌身份验证,您只需要根据您的请求传递实际令牌:无用户名,无密码。在测试代码时,我可以看到token
值为prova
,而您需要blabla
(这是实际的令牌值)。
您可以在pdb
中添加check_auth
断点来验证自己。因此,请尝试将YmxhYmxhOg==
(blabla)与您的Auth请求标头一起使用。