python - 401 when trying to authenticate user in Eve flask framework -
i'm using awesome eve rest-framework creating crud api jwt authentication. i've looked @ tutorials posted here i'm receiving 401 error when doing post request endpoints require token auth.
i've read question: issue python eve tokenauth feature i'm pretty sure token base64 encoded.
this response i'm getting server when doing curl request:
curl -h "authorization: <mytoken>" -i http://my_ip/users/548f6ecd64e6d12236c9576b ---- response ---- http/1.1 401 unauthorized server: nginx/1.4.6 (ubuntu) date: tue, 16 dec 2014 10:49:25 gmt content-type: application/json content-length: 91 connection: keep-alive www-authenticate: basic realm:"eve" {"_status": "err", "_error": {"message": "please provide proper credentials", "code": 401}}
below code:
app.py
from eve import eve eve.auth import tokenauth import jwt class rolesauth(tokenauth): def check_auth(self, token, allowed_roles, resource, method): users = app.data.driver.db['users'] # add check of user credentials decoding jwt user = users.find_one({'token': token}) return user def add_token(documents): document in documents: payload = {'username': document['username']} document["token"] = jwt.encode(payload, 'secret') if __name__ == '__main__': app = eve(auth=rolesauth) app.on_insert_users += add_token app.run()
settings.py
users_schema = { 'username': { 'type': 'string', 'required': true, }, 'password': { 'type': 'string', 'required': true, }, 'email': { 'type': 'string', 'minlength': 1, 'maxlength': 200, 'required': true, }, 'token': { 'type': 'string', }, 'created': { 'type': 'datetime', } } users = { 'cache_control': '', 'cache_expires': 0, 'extra_response_fields': ['token'], 'public_methods': ['post'], 'schema': users_schema } domain = { 'users': users, }
i have token stored in mongodb user , i'm making request postman , i'm including token in authorization header so:
authorization: <usertoken>
any thoughts on why gives me 401.
thanks!
i tested code but, simplicity, got rid of jwt.encode
:
def add_token(documents): document in documents: payload = {'username': document['username']} document["token"] = 'hello'
i posted new user /users
, did same endpoint postman: works charm (200
). did same test curl
:
curl -h "authorization: basic y2lhbzo=" -i http://localhost:5000/users
that retuns 200
. can see auth header encoded (copy & paste postman request preview). make sure passing right stuff, maybe set breakpoint in check_auth
validate what's coming , wether db lookup successful or not.
hope helps in diagnosing issue.
ps: please note in curl authorization header has basic
statement before token, seems lacking in code snippet.
update
for sake of installed pyjwt , tested code and... works fine on end. must wrong request.
update2
one thing might not obvious still need append (encoded) :
auth header (it's basic auth , parses both username , pw). that's why in above example have =
@ end of encoded 'hello'.
Comments
Post a Comment