sibstudent1
sibstudent1

Reputation: 59

How to send and receive JWT token?

Trying to verify user's token.

How I'm making a request on the client side (js + react):

axios({
        method: 'POST',
        url: '/verify', 
        headers: { authorization: sessionStorage.getItem('token') },
        data: {}
    })
        .then(function(response) {
            // ...
        });

How I'm receiving a request on the server side (python):

@app.route('/verify', methods=['POST'])
def verify_user():
    token = request.headers.get('Authorization')
    payload = jwt.decode(token, SECRET_KEY)  // error here
    // ...

Why do I get this error? :

Traceback (most recent call last):
........
jwt.exceptions.DecodeError: Signature verification failed

Thank you in advance.

p.s. the token is sent correctly


EDIT:

Found the causer of the mistake:

@app.route('/login', methods=['POST'])
def get_user():
    // ...
    token = jwt.encode({'some': 'payload'}, 'secret', algorithm='HS256')
    return token // when I return the token here, it becomes slightly reduced

real token:

b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzb21lIjoicGF5bG9hZCJ9.Joh1R2dYzkRvDkqv3sygm5YyK8Gi4ShZqbhK2gxcs2U'

the reduced token I return:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzb21lIjoicGF5bG9hZCJ9.Joh1R2dYzkRvDkqv3sygm5YyK8Gi4ShZqbhK2gxcs2U

How do I need to send generated jwt token to client to fix that?

Upvotes: 1

Views: 4771

Answers (1)

Matt Morgan
Matt Morgan

Reputation: 5313

This looks like a string-vs-bytes encoding issue. To decode a byte string:

str = byte_string.decode('UTF-8')  # turns b'123' into '123'

To encode the string to bytes:

byte_string = str.encode('UTF-8')  # turns '123' into b'123'

You probably need to encode the incoming string to bytes before you pass it to jwt.decode() like so:

jwt.decode(token.encode('UTF-8'), SECRET_KEY)

There are other encodings besides UTF-8, but that will probably be what you need.

Upvotes: 2

Related Questions