0

I'm currently facing some confusion regarding token refreshing in my website. I've implemented JWT (JSON Web Tokens) with an extended expiration time, and I store these tokens in cookies.

My objective is to automatically refresh the token whenever a user attempts to access a protected route with an expired token. After refreshing the token, the user should be redirected to the original page they intended to visit.

I'm uncertain about how to check if the token is expired with every request, and I'm also unsure about the process of redirecting the user after token refreshment.

Config

app.config['JWT_TOKEN_LOCATION'] = ['cookies']
app.config['JWT_COOKIE_SECURE'] = True
app.config['JWT_SECRET_KEY'] = 'jwt-secret-string'
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = datetime.timedelta(seconds=5)
app.config['JWT_REFRESH_TOKEN_EXPIRES'] = datetime.timedelta(days=7)
app.config['JWT_COOKIE_CSRF_PROTECT'] = True

Login Route

@app.route('/login', subdomain='panel', methods=['POST', 'GET'])
@jwt_required(optional=True)
# @limiter.limit("5/minute") 
def login():

    data = request.get_json()

    username = data.get('username', None)
    password = data.get('password', None)
    remember = data.get('remember_me', False)

    users = db["users"]["users"]

    if not username or not password:
        abort(400, description="Missing username/email or password")

    user = users.find_one({'username': username})

    if user and bcrypt.check_password_hash(user['password'], password):
        access_token = create_access_token(identity=user['username'])

        if remember:
            refresh_token = create_refresh_token(identity=username, expires_delta=datetime.timedelta(days=7))
        else:
            refresh_token = create_refresh_token(identity=username, expires_delta=datetime.timedelta(hours=24))

        resp = make_response(jsonify({'success': True}))
        resp.status_code = 302
        resp.set_cookie('access_token_cookie', access_token, httponly=True)
        resp.set_cookie('refresh_token', refresh_token, httponly=True)
        
        return resp

    else:
        return jsonify({"msg": "Bad username/email or password"}), 401

Refresh Route

@app.route('/token/refresh', subdomain='panel', methods=['GET'])
@jwt_refresh_token_required
def refresh():
    # Refreshing expired Access token
    user_id = get_jwt_identity()
    access_token = create_access_token(identity=str(user_id))
    resp = make_response(redirect('/', 302))
    set_access_cookies(resp, access_token)
    return resp

Protected exmaple route

@app.route('/dashboard', subdomain='panel', methods=['GET'])
@jwt_required()
def dashboard():
    username = get_jwt_identity()
    
    return render_template(
        'panel/dashboard.html',
        username=username,
    ), 200
GoekhanDev
  • 326
  • 2
  • 4
  • 20

0 Answers0