我正在尝试进行身份验证并获取访问令牌。我创建了用户类,我试图在身份验证时从 POSTMAN 运行 POST 方法,但我收到一些错误:
{
"description": "Invalid credentials",
"error": "Bad Request",
"status_code": 401
}
我找不到任何解决方案。
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)
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)
user.py 的代码
class User:
def __init__(self,_id,username,password):
self.id = _id
self.username = username
self.password = password
如您所见,我已经正确实现了代码,但我仍然收到此“无效凭据”或“错误请求”错误。