10

So I have a simple flask app. Logging in creates a token:

token = jwt.encode({'user': token_data}, app.config['SECRET_KEY']).decode('utf-8')

The middleware looks like this:

def token_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        data = request.headers['Authorization'].encode('ascii', 'ignore')
        token = str.replace(str(data), 'Bearer ', '')
        if not token:
            return jsonify({'message': 'Token is missing'}), 401
        data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])['sub']
        return f(*args, **kwargs)

    return decorated

Then I run a protected route that is @token_required and get the error. jwt.exceptions.DecodeError: Invalid header padding

Can't add another utf-8 to the middleware token, as I cant use it with str What can I do?

4
  • Aren’t you missing a closing bracket on the first arg to jwt encode? Commented Jul 14, 2020 at 16:01
  • no, it was a typo, sorry, I have it in my original code. Commented Jul 14, 2020 at 18:12
  • Why is your token being decoded during creation? Commented Jul 14, 2020 at 18:23
  • Decoding with utf-8 is needed. It can be put either in the middleware or during the creation. As my token is type str in the middleware I cant decode it with utf-8 Commented Jul 15, 2020 at 13:14

1 Answer 1

3

So I removed .encode('ascii', 'ignore') and also ['sub'] and it seems to work

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.