Search code examples
pythonjwtflask-restful

How to send jwt token in json format?


I'm trying to figure out API with python. And want to send back some already encrypted jwt token.

When I'm trying to return jwt token in return method sends back Error's and Error's page in postman app shows up. But when printing it inside console everything works fine.

class Login(Resource):
    def post(self):
        json_data = request.get_json(force=True)
        un = json_data['username']
        pw = json_data['password']
        encoded_jwt = jwt.encode({'username': un, 'password': pw}, 'OH HI MARK', algorithm='HS256')
        print(encoded_jwt)
        return jsonify(token = encoded_jwt)

I'm excpecting to get this token `

b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImhpIiwicGFzc3dvcmQiOiJwYXNzd29yZCJ9.MQ-hwWabt13E4KMFxPztSUr6RYwsZZ-tT0sdv2s0vU0'

But getting bunch of error.

Edit: Asked to add Error's.

Traceback (most recent call last):
  File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 2309, in __call__
    return self.wsgi_app(environ, start_response)
  File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 2295, in wsgi_app
    response = self.handle_exception(e)
  File "D:\FinallySomethingWork\venv\lib\site-packages\flask_restful\__init__.py", line 269, in error_router
    return original_handler(e)
  File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 1741, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "D:\FinallySomethingWork\venv\lib\site-packages\flask\_compat.py", line 34, in reraise
    raise value.with_traceback(tb)
  File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "D:\FinallySomethingWork\venv\lib\site-packages\flask_restful\__init__.py", line 269, in error_router
    return original_handler(e)
  File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "D:\FinallySomethingWork\venv\lib\site-packages\flask\_compat.py", line 34, in reraise
    raise value.with_traceback(tb)
  File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "D:\FinallySomethingWork\venv\lib\site-packages\flask_restful\__init__.py", line 458, in wrapper
    resp = resource(*args, **kwargs)
  File "D:\FinallySomethingWork\venv\lib\site-packages\flask\views.py", line 88, in view
    return self.dispatch_request(*args, **kwargs)
  File "D:\FinallySomethingWork\venv\lib\site-packages\flask_restful\__init__.py", line 573, in dispatch_request
    resp = meth(*args, **kwargs)
  File "D:\FinallySomethingWork\Yeah\app.py", line 16, in post
    return jsonify(token = encoded_jwt)
  File "D:\FinallySomethingWork\venv\lib\site-packages\flask\json\__init__.py", line 321, in jsonify
    dumps(data, indent=indent, separators=separators) + '\n',
  File "D:\FinallySomethingWork\venv\lib\site-packages\flask\json\__init__.py", line 179, in dumps
    rv = _json.dumps(obj, **kwargs)
  File "C:\Users\Denis\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "C:\Users\Denis\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 201, in encode
    chunks = list(chunks)
  File "C:\Users\Denis\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 431, in _iterencode
    yield from _iterencode_dict(o, _current_indent_level)
  File "C:\Users\Denis\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 405, in _iterencode_dict
    yield from chunks
  File "C:\Users\Denis\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 438, in _iterencode
    o = _default(o)
  File "D:\FinallySomethingWork\venv\lib\site-packages\flask\json\__init__.py", line 81, in default
    return _json.JSONEncoder.default(self, o)
  File "C:\Users\Denis\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type bytes is not JSON serializable

Solution

  • The error message says:

    TypeError: Object of type bytes is not JSON serializable

    That means, encoded_jwt is a byte array which can't be serialized into a JSON. You first have to convert it to a string:

    return jsonify(token = encoded_jwt.decode("utf-8"))
    

    On a sidenote: don't put the password into the token!