问题
I am currently testing the python-eve library since a few days to create a restful API but I'm experiencing some issues when I follow this tutorial to implement a "Token Authentication".
Here is my user schema:
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,
}
}
Here is my user domain configuration:
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
}
And here is the code I run to test my 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()
My problem is when I try to make a request on the users endpoint like this
curl -X GET "http://localhost:5000/users" -H "Content-Type: application/json" -H "Authorization: Basic <MY_TOKEN>"
With the as the token actually stored in the users collection, I always got the following error:
Please provide proper credentials
And on the API logs:
127.0.0.1 - [29/Jun/2014 03:12:32] "GET /users HTTP/1.1" 401 -
Here is a sample of what I have in mongodb for the user's token that I use for this example:
{
"username" : "cmorent",
"password" : "<MY_PASSWORD>"
"roles" : [
"sudo",
"admin",
"user"
],
"token" : "<MY_TOKEN>"
}
Do you guys have any idea of what I am doing wrong? Is this something wrong with the Authorization header that I send?
Thank you guys for your help!
回答1:
Have you properly encoded the token being sent with your request? Basic/Token auth want it Base64-encoded. I suggest you experiment with some kind of client (like Postman in Chrome) so you can see what actually is going on and how the auth token is being encoded.
来源:https://stackoverflow.com/questions/24472439/issue-with-the-python-eve-tokenauth-feature