8

this is my code

@app.route("/api/v1.0/login", methods=["GET"] )
def login():
    auth = request.authorization
    if auth:
        user = users.find_one( { "username" : auth.username } )
        if user is not None:
            if bcrypt.checkpw(bytes(auth.password, 'UTF-8'), user["password"]):
                token = jwt.encode({
                    'user' : auth.username,
                    'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=30)}, app.config['SECRET_KEY'])
                return make_response( jsonify({'token' : token.decode('UTF-8')}), 200)
            else: 
                return make_response(jsonify({"message" : "Bad password"} ) )
        else: 
            return make_response(jsonify({"message" : "Bad username" } ) )

    return make_response(jsonify({ "message" : "Authentication required"}))

and this is error

AttributeError: 'str' object has no attribute 'decode'

Kevin Bradley
  • 91
  • 1
  • 1
  • 2

2 Answers2

15

If you are using PyJwt module, then there is no need to decode the token. jwt.encode({some_dict}) returns the token you need.

therealak12
  • 1,178
  • 2
  • 12
  • 26
3

this worked for me, i only returned the token (i initially had 'return token.decode('utf-8')' but later took the decode function off)

   def _generate_jwt_token(self):
        dt = datetime.now() + timedelta(days=60)
        token = jwt.encode({
            'id': self.pk,
            'exp': dt.utcfromtimestamp(dt.timestamp())},
            settings.SECRET_KEY, algorithm='HS256')
        return token
Benjamin Andoh
  • 285
  • 2
  • 8