helpjpls
helpjpls

Reputation: 11

How to pass jwt token from one route to another?

I am new to coding. I have set up a login function within Flask using flask-JWT. Thus far, I am able to login (on "/login") and a token is generated using jwt.

However, I have other routes which are also protected using a wrapper (@token_required). I would like to make it such that once users have logged in, the token will be passed to the other protected pages which they will then be able to access.

These are my codes:

wrapper to protect page

def token_required(f):                      #wrapper for token auth
    @wraps(f)
    def decorated(*args, **kwargs):
        token = request.args.get('token')

        if 'x-access-token' in request.headers:
            token = request.headers['x-access-token']

        if not token:
            return jsonify({'message': 'Token is missing!'}), 401
        
        try:
            data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"])
            current_u = User.query.filter_by(username=data['user']).first()    
            #identify user, otherwise, return error

        except:
            return jsonify({'message': 'Token is invalid!'}), 401
        
        return f(current_u, *args, **kwargs)   #previously return f(*args, **kwargs)

    return decorated

login route

@app.route('/login', methods=['GET', 'POST'])        #login route
def login():
    auth = request.authorization

    if not auth or not auth.username or not auth.password:
        return make_response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm = "Login Required!"'})

    user = User.query.filter_by(username=auth.username).first()

    if not user:
            return make_response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm = "Login Required!"'})

    if user.check_password(auth.password): 
        token = jwt.encode({'user': auth.username, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=2)}, app.config['SECRET_KEY'])
        
        return jsonify({'message': 'hello ' + user.username}, {'token': token})

    return make_response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm = "Login Required!"'})

protected route using wrapper

@app.route('/protected')           #protected routes
@token_required
def protected(current_u):
    return jsonify({'message' : 'This is only for people with valid tokens'})

I am just stuck at this point in time as I can't quite find tutorials specifically for this / maybe its also an issue with not knowing what to search for. Could anyone help me out please?

Upvotes: 0

Views: 1140

Answers (1)

vinzenz
vinzenz

Reputation: 689

on further thougt I dont think using session is necessary as the authentication is encoded in the jwt token. I think you bug is in the decorator

try:
        data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"])
    except:
        return jsonify({'message': 'Token is invalid!'}), 401

This is except clause is to broad, what exceptions need to be handled here?

Upvotes: 0

Related Questions