DEV Community

Free Python Code
Free Python Code

Posted on

[SOLVED] jwt.exceptions.DecodeError: Invalid header padding error

Hi πŸ™‚πŸ–

I faced this error, and I want to share the solution with you. πŸ€—

This my code :


from fastapi import FastAPI, Response, Request, Depends
from fastapi.responses import HTMLResponse
import jwt

app = FastAPI()

def generate_jwt():
    return jwt.encode({'id':'test'}, key = '123', algorithm='HS256')


def decode_token(token):
    payload = jwt.decode(token, key = '123', algorithm='HS256')
    return payload


@app.get('/test')
async def test(response: Response):
    response = HTMLResponse(open('test.html', 'r').read())
    response.set_cookie(key="fakesession", value=generate_jwt())

    return response


async def read_token(request : Request):
    token = request.cookies.get('fakesession')
    if not token:
        return False

    return decode_token(token)

@app.get('/protected')
async def protected(token : str = Depends(read_token)):
   return token

Enter fullscreen mode Exit fullscreen mode

I have this error : jwt.exceptions.DecodeError: Invalid header padding

And this is the solution :
Just add .decode('utf-8') to convert it to string

def generate_jwt():
    return jwt.encode({'id':'test'}, key = '123', algorithm='HS256').decode('utf-8')
Enter fullscreen mode Exit fullscreen mode

https://github.com/jpadilla/pyjwt/issues/319

Top comments (0)