Reputation: 11
I am trying to authenticate and get an access token. I have created user class, I am trying to run the POST method from POSTMAN while authenticating, but I am receiving some error:
{
"description": "Invalid credentials",
"error": "Bad Request",
"status_code": 401
}
and I couldn't find any solution.
Code for app.py
from flask import Flask, request
from flask_restful import Resource, Api
from flask_jwt import JWT, jwt_required
from security import authenticate, identity
# creating flask app
app = Flask(__name__)
app.secret_key = 'vishwas'
api = Api(app)
jwt = JWT(app, authenticate, identity) # /auth
# empty list of items
items = []
class Item(Resource):
@jwt_required()
def get(self,name):
# next return first value that found by the filter function
# next(filter(), None) -> 'None' to handle the eroor if the list is empty
item = next(filter(lambda x: x['name'] == name,items), None)
return {'item': item}, 200 if item else 404
# http://127.0.0.1.5000/item/<string:name>
api.add_resource(Item, '/item/<string:name>')
app.run(port=5000, debug=True)
Code for security.py
from werkzeug.security import safe_str_cmp
from user import User
# list of users
users = [
User(1,"bob","pass")
]
# users information using their username
username_mapping = {user.username: user for user in users}
# users information using their userid
userid_mapping = {user.id: user for user in users}
def authenticate(username,password):
user = userid_mapping.get(username, None)
if user and safe_str_cmp(user.password, password):
return user
def identity(payload):
user_id = payload['identity']
return userid_mapping.get(user_id, None)
Code for user.py
class User:
def __init__(self,_id,username,password):
self.id = _id
self.username = username
self.password = password
As you can see that I have implemented the code correctly but still I am getting this 'Invalid Credentials' or 'Bad Request' error.
Upvotes: 0
Views: 3546
Reputation: 1
Make sure to use username instead of name
"name": "mostafa",
"password": "pass"
}
should be this
"username": "mostafa",
"password": "pass"
}
Upvotes: 0
Reputation: 111
if you look at what is stored in the data:
def authenticate(username, password):
print(username_mapping)
we will see:
{('bob',): <user.User object at 0x000002C7DC982B00>}
that is, the ('bob',) key, not bob I myself only study potshon, so the decision to make only this
def authenticate(username, password):
user = username_mapping.get(('{}'.format(username),), None)
if user and safe_str_cmp(user.password, password):
return user
And you mistake there, instead username_mapping, you're using userid_mapping And accordingly:
def identity(payload):
user_id = payload['identity']
return userid_mapping.get((user_id[0],), None)
I don’t know how much is correct, most likely it is necessary to bring the initial data to the correct type, but it works. Maybe someone will tell you how it is more correct.
Upvotes: 1