0

我正在尝试进行身份验证并获取访问令牌。我创建了用户类,我试图在身份验证时从 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

如您所见,我已经正确实现了代码,但我仍然收到此“无效凭据”或“错误请求”错误。

4

2 回答 2

0

确保使用用户名而不是名称

    "name": "mostafa",
    "password": "pass"
}

应该是这个

    "username": "mostafa",
    "password": "pass"
}
于 2020-11-15T00:15:44.140 回答
0

如果您查看数据中存储的内容:

def authenticate(username, password):
    print(username_mapping)

我们会看到:

{('bob',): <user.User object at 0x000002C7DC982B00>}

也就是 ('bob',) 键,不是 bob 我自己只研究potshon,所以决定只做这个

def authenticate(username, password):
    user = username_mapping.get(('{}'.format(username),), None)
    if user and safe_str_cmp(user.password, password):
        return user

你错了,而不是username_mapping,你正在使用userid_mapping 相应地:

def identity(payload):
    user_id = payload['identity']
    return userid_mapping.get((user_id[0],), None)

我不知道多少是正确的,很可能需要将初始数据转换为正确的类型,但它可以工作。也许有人会告诉你如何更正确。

于 2020-06-19T15:55:28.717 回答