jwt python无法为用户添加令牌

时间:2018-05-07 11:35:13

标签: python-3.x flask jwt flask-jwt-extended

我正在做一个简单的项目,我想添加jwt身份验证。 当我登录时,我尝试创建一个新令牌,但是当我试图查看用户使用令牌的用户时,它表示该令牌丢失了。

我正在使用Flask和SQLAlchemy和Postgresql

app.py

app.config['JWT_TOKEN_LOCATION'] = ['cookies']
#app.config['JWT_COOKIE_SECURE'] = False
app.config['JWT_ACCESS_COOKIE_PATH'] = '/api/'
app.config['JWT_REFRESH_COOKIE_PATH'] = '/token/refresh'
app.config['JWT_COOKIE_CSRF_PROTECT'] = False
app.config['JWT_SECRET_KEY'] = 'abva'

jwt = JWTManager(app)

@app.route('/token/auth', methods=['POST'])
def login():
    email = request.form['email']
    password = request.form['password']
    user = User.query.all()
    for user in user: 
        if user.email == email and user.password == password:
            access_token = create_access_token(identity=user.email)
            refresh_token = create_refresh_token(identity=user.email)
            # Set the JWTs and the CSRF double submit protection cookies
            # in this response
            resp = jsonify({'login': True})
            set_access_cookies(resp, access_token)
            set_refresh_cookies(resp, refresh_token)
            return resp, 200


    return jsonify({'login': False}), 401  


@app.route('/protected', methods=['GET'])
@jwt_required
def protected():
    ret = {
        'current_identity': get_jwt_identity(),  # test
    }
    return jsonify(ret), 200


@app.route('/token/remove', methods=['POST'])
def logout():
    resp = jsonify({'logout': True})
    unset_jwt_cookies(resp)
    return resp, 200

@jwt.user_identity_loader
def user_identity_lookup(user):
    return user

add_user.html

<!DOCTYPE html>
<html>
<body>
    <form method="POST" action="/token/auth">
        <label> Email: </label>
        <input id="email" name ="email" type="text" />
        <label> Password: </label>
        <input id="password" name ="password" type="password" />
        <input type="submit" />
    </form>
    <form method="POST" action="/token/remove">
        <input type="submit" value="LogOut" />
    </form>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

你的路线是/受保护的,但你的JWT_ACCESS_COOKIE_PATH是/ api /。这将阻止cookie被发送到该端点。将端点更改为/ api / protected,或将cookie路径更改为/