EVE REST- Issue with AuthToken in python Eve framework error 401

415 views Asked by At

I am currently working on python-eve library to create a restful API but I'm experiencing some issues when I follow this tutorial to implement a "Token Authentication" I get error 401 saying "please provide proper credential".

Here is my user schema:

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

DOMAIN = {
'user': {
    'additional_lookup': {
            'url': 'regex("[\w]+")',
            'field': 'username',
            #'url': '[\w]+',
        },
    'schema': {
        'firstname': {
            'type': 'string'
        },
        'lastname': {
            'type': 'string'
        },
        'phone': {
            'type': 'string'
        },
        'username': {
            'type': 'string',
            'required': True,
            'unique': True,
        },
        'password': {
            'type': 'string',
            'required': True,
        },
        'roles': {
            'type': 'list',
            'allowed': ['user', 'superuser', 'admin'],
            'required': True,
        },
        'token': {
            'type': 'string',
            'required': True,
        }
    },

    'cache_control': '',
    'cache_expires': 0,
    'allowed_roles': ['superuser', 'admin'],
    },

'item': {
    'schema': {
        'name':{
            'type': 'string'
            },
        'username': {
            'type': 'string'
            }
        }
    },

}

Here is my app.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):
    accounts = app.data.driver.db['eve']
    lookup = {'token': token}
    if allowed_roles:
        lookup['roles'] = {'$in': allowed_roles}
    account = accounts.find_one(lookup)
    return account

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

app = Eve(settings='settings.py')

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

Any ideas why am ending up with a 401.

am using python 3.4

If possible please provide me with working code. I am a noob in this field.

Thanks!

1

There are 1 answers

0
Mandar Vaze On

You need to encode the token as follows:

echo "54321:" | base64

Please do not forget last :

Since you are directly looking up the token (per your code), username is not needed.