0

Im trying to attach a token to a logged in user:

user_info = request.get_json()
entered_username = User.query.filter_by(username = user_info['username']).first()
        if user_info['password'] == entered_username.password:                                                                  
            token = jwt.encode({'username':entered_username, 'exp':datetime.datetime.utcnow() + datetime.timedelta(minutes=30)},
                               secret_key, algorithm='HS256').decode('UTF-8')
        return jsonify(token) 

But i get: TypeError: Object of type 'User' is not JSON serializable. I've also tried to do return jsonify(token.decode('UTF-8'))

What am i missing?

4
  • Just what is says: you can't encode a User object to JSON and entered_username is a User object. If you just want the username in your token, encode {'username': user_info['username'], ...}. Commented Jun 4, 2020 at 17:34
  • Do you mean the whole thing? I tried {'username': user_info['username'], ...}.decode('UTF-8') but then i get AttributeError: 'dict' object has no attribute 'decode' Commented Jun 4, 2020 at 17:54
  • Yes, the ellipsis meant the rest of your code, not literally a .... I'm also not sure why you're trying to call decode here. Commented Jun 4, 2020 at 18:07
  • No i meant the rest of the {} or the rest of the entire code. not ... haha. I get the same thing for encode. Commented Jun 4, 2020 at 18:12

1 Answer 1

2

You can't encode a User object to JSON and entered_username is a User object. If you just want the username in your token, you can do something like this:

user_info = request.get_json()
user_obj = User.query.filter_by(username = user_info['username']).first()
if user_info['password'] == user_obj.password:
    claims = {
        'username': user_info['username'], # or perhaps user_obj.username
        'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30)
    }

    token = jwt.encode(claims, secret_key, algorithm='HS256')

    # Maybe some error checking here?

    response = {
        'token': token.decode()
    }

    return jsonify(response)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.