Zichittella
Zichittella

Reputation: 51

Is it possible to change the _default_jwt_payload_handler(identity) by code?

I'm having problems using Flask-JWT in my application, I am using the authenticate and identity like this:

def authenticate(username, password):
  session = db.Session()
  user = session.query(db.Operators).filter_by(username= username).first()
  if user and bcrypt.check_password_hash(user.password, password):
    return user

def identity(payload):
  user_id = payload['identity']
  session = db.Session()
  return session.query(db.Operators).filter_by(idOperator= user_id)

But I get an error because I do not have an id field in my db table because I have an idOperator

How can I solve this problem? The _default_jwt_payload_handler(identity) function goes to seek for an Id field, how can I change this automatic id field to an IdOperator without changing the init.py of flask-jwt?

Thanks

Upvotes: 1

Views: 236

Answers (2)

vimalloc
vimalloc

Reputation: 4167

You might want to consider flask-jwt-extended instead. Flask-JWT has been abandoned for years now, whereas flask-jwt-extended is still actively maintained and much easier to customize: https://flask-jwt-extended.readthedocs.io/en/latest/basic_usage.html

Upvotes: 0

Halvor Holsten Strand
Halvor Holsten Strand

Reputation: 20536

You can use the jwt_payload_handler decorator to specify your own payload handler.

For example, mimicing the default behavior but instead using idOperator could look like this:

jwt = JWT(app, authenticate, identity)

@jwt.jwt_payload_handler
def make_payload(identity):
    iat = datetime.utcnow()
    exp = iat + current_app.config.get('JWT_EXPIRATION_DELTA')
    nbf = iat + current_app.config.get('JWT_NOT_BEFORE_DELTA')
    identity = getattr(identity, 'idOperator') or identity['idOperator']
    return {'exp': exp, 'iat': iat, 'nbf': nbf, 'identity': identity}

Which uses:

from datetime import datetime
from flask import current_app

Here is the documentations specification.

Upvotes: 0

Related Questions