'KeyError while passing token in session

Below is the decorator function for checking the token in the session

def token_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if not session['token'] :
            return jsonify({"error":"wrong t0k3n"}) , 401
        else :
            try:
                # decode the token 
                data = jwt.decode(session['token'], current_app.config['SECRET_KEY'])
                return jsonify({"error":"0k"}), 201
            except:
                return jsonify({"error":"wrong t0k3n"}) , 401
        return  f(current_user, *args, **kwargs)
    return decorated

@webui.route('/login', methods=['GET' , 'POST'])
def login():
    if request.method == "POST":
        email = request.form.get('email')
        user = User.query.filter_by(email=email).first()
        password = request.form.get('password')
        if not user or not check_password_hash(user.password, password):
            flash('Please check your login details and try again.')
            return render_template('login.html') 
        else:
            session['username'] = user.username
            token = jwt.encode({'username': user.username , 'exp' : datetime.utcnow() + timedelta(minutes=2880)}, current_app.config['SECRET_KEY'])  
            session['token'] = token 
            print (session['token'])
            return redirect(url_for('webui.home'))
        return render_template('login.html')
    else:
        return render_template('login.html')

when a user logs in the token is saved in the session but the decorator can't access the token

The below route takes the arguments passed in a POST request and commits them to the database


 
@webui.route('/Edit/<id>', methods=['POST'])
@token_required
def Edit(id):
    user = User.query.get(id)
    if request.method == 'POST':
        if user:
            user.first = request.args['first']
            user.last = request.args['last']
            db.session.commit()
            return jsonify({"success":"ok"}) , 201 
        elif not usr: 
            return jsonify({"error":" Name not found  "}) , 401

    else:
        return jsonify({"error":"error"}), 401

Now when using postman to make this request 127.0.0.1:5000/edit/1?first=first&last=last a 500 KeyError error is thrown stating that the token is not found



Solution 1:[1]

I had this same issue and this page helped https://pythonbasics.org/flask-sessions/.
Try changing

if not session['token'] :

to:

if not 'token' in session:

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 wandored