"Not enough segments" when seding a GET message with Bearer Token Authorization Header (flask_restful + flask_jwt_extended)
Asked Answered
A

4

16

I got this error in Flask Application:

curl http://0.0.0.0:8080/ -H "Authorization: Bearer TGazPL9rf3aIftplCYDTGDc8cbTd"
{
  "msg": "Not enough segments"
}

Here a sample:

from flask import Flask
from flask_restful import Resource, Api
from flask_jwt_extended import JWTManager, jwt_required

app = Flask(__name__)
jwt = JWTManager(app)
api = Api(app)


class HelloWorld(Resource):
    @jwt_required
    def get(self):
        return {'hello': 'world'}


api.add_resource(HelloWorld, '/')

Console:

 * Serving Flask app "app.py" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 890-265-009
127.0.0.1 - - [26/Apr/2020 02:02:32] "GET / HTTP/1.1" 422 -

I can't understand: What's wrong?

The exception has been thrown in other lib (line 183 in site-packages/jwt/api_jws.py):

  def _load(self, jwt):
        if isinstance(jwt, text_type):
            jwt = jwt.encode('utf-8')

        if not issubclass(type(jwt), binary_type):
            raise DecodeError("Invalid token type. Token must be a {0}".format(
                binary_type))

        try:
            signing_input, crypto_segment = jwt.rsplit(b'.', 1)
            header_segment, payload_segment = signing_input.split(b'.', 1)
        except ValueError:
            raise DecodeError('Not enough segments')
Akkerman answered 26/4, 2020 at 5:5 Comment(0)
C
21

The token you are trying to pass in (TGazPL9rf3aIftplCYDTGDc8cbTd)is not a valid JWT. A valid JWT has three segments separated by dots: <base64_encoded_header>.<base64_encoded_payload>.<signature>. You can read more about it here: https://jwt.io/introduction/

Conditioning answered 26/4, 2020 at 13:57 Comment(0)
A
4

I will post here an answer related to my initial problem above, the context is that I was trying to user flask_jwt_extend to use in firebase authentication, but I have this "Not enough segments" errors and I got blocked.

So after that, I change my code to:

from flask import Flask, request
from flask_restful import Resource, Api
from functools import wraps
import google.auth.transport.requests
import google.oauth2.id_token

app = Flask(__name__)
api = Api(app)
HTTP_REQUEST = google.auth.transport.requests.Request()


def jwt_required_gcp(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        id_token = request.headers['Authorization'].split(' ').pop()
        claims = google.oauth2.id_token.verify_firebase_token(
            id_token, HTTP_REQUEST)
        if not claims:
            return 'Unauthorized', 401
        return fn(*args, **kwargs)
    return wrapper


class HelloWorld(Resource):
    @jwt_required_gcp
    def get(self):
        return {'hello': 'world'}


api.add_resource(HelloWorld, '/')
Akkerman answered 27/4, 2020 at 1:59 Comment(0)
R
1

Check your JWT Token. Is it valid?

@fresh_jwt_required - fresh_jwt_required() function to only allow fresh tokens to access the certain endpoint

@jwt_required - A decorator to protect a Flask endpoint with JSON Web Tokens. Any route decorated with this will require a valid JWT to be present in the request (unless optional=True, in which case no JWT is also valid) before the endpoint can be called.

For more detail review flask-jwt-extended

Retroflex answered 1/7, 2021 at 10:18 Comment(1)
It’s not valid as the above marked answer (from vimalloc)Akkerman
K
0

The new version of flask-jwt-extended > 4.0.0 replaced @jwt_required with @jwt_required().

If you are using the latest version of flask-jwt-extended then use @jwt_required() and ensure that your JWT is valid.

A valid JWT contains 3 parts likes below,

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTY4NzgzNDAyOSwianRpIjoiMTQ0NjA1MTAtYzJlOS00NzJiLTk3OTctMjAzZDNiMDdjYjk5IiwidHlwZSI6ImFjY2VzcyIsInN1YiI6ImFkbWluIiwibmJmIjoxNjg3ODM0MDI5LCJleHAiOjE2ODc4MzQ5Mjl9.0x_NmlXa-9lBXVea79S1Oae9PEaW7DLYZ1yFhviO1Uc 

You can checkout the following repository, it contains basic flask-jwt-extended demo.

https://github.com/codemaker2015/flask-jwt-extended-demo

Khan answered 27/6, 2023 at 3:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.