1

i´m doing a simple project where I want to add jwt authentication. When I log in I try to create a new token but when i´m trying to see who´s the user using the token it says that the token is missing.

I´m using Flask and SQLAlchemy with 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>
Ricardo Pinto
  • 333
  • 1
  • 2
  • 11
  • Is the cookie actually saved client side? – Ron Nabuurs May 07 '18 at 11:42
  • You should not do User.query.all here, that is horribly inefficient. You should query for the specific use that is specified as the username. More importantly, the password should not be stored and compared using plain text in your database. You should be using a password hashing algorithm (such a bcrypt or argon2) in conjunction with a salt. – vimalloc May 07 '18 at 14:01

1 Answers1

0

Your route is /protected but your JWT_ACCESS_COOKIE_PATH is /api/. That will prevent the cookie from being sent to that endpoint. Either change the endpoint to /api/protected, or change the cookie path to just /

vimalloc
  • 3,869
  • 4
  • 32
  • 45