10

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'

3
  • 1
    And your question is? You can only encode a string. Commented Jan 19, 2021 at 19:35
  • What kind of object is jwt? Commented Jan 19, 2021 at 19:39
  • Strings will be encoded and bytes will be decoded. Commented Jan 19, 2021 at 19:56

2 Answers 2

17

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

Sign up to request clarification or add additional context in comments.

Comments

6

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

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.