Jwt decode error

You're viewing Apigee X documentation. View Apigee Edge documentation.


You’re viewing Apigee X documentation.
View
Apigee Edge documentation.

FailedToDecode

Error code

steps.jwt.FailedToDecode

Error response body

{
  "fault": {
    "faultstring": "Failed to Decode Token: policy({0})",
    "detail": {
       "errorcode": "steps.jwt.FailedToDecode"
     }
  }
}

Cause

This error occurs if the JSON Web Token (JWT) specified in the <Source> element of the Decode JWT policy is malformed, invalid or otherwise not decodable.

A properly structured JWT should contain a header, payload and signature in the following format: header.payload.signature. If the JWT passed to the DecodeJWT policy is missing a component part, then you will get the error. For example, if the JWT has only payload.signature, but is missing its header, the error will occur.

Diagnosis

  1. Identify the variable specified in the <Source> element of the Decode JWT policy. This variable should contain the JWT.

    Here’s a sample Decode JWT policy:

    <DecodeJWT name="JWT-Decode-HS256">
        <DisplayName>JWT Verify HS256</DisplayName>
        <Source>request.header.authorization</Source>
        <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
    </DecodeJWT>
    

    In the above example, the JWT should be contained in the Authorization request header.

  2. Examine the variable identified in Step 1 and check to see if the JWT it contains is valid. If the input JWT is not valid, then that’s the cause for the error.

    In the example API request below, the input JWT is passed in the Authorization request header:

    curl -v "http://$EXTERNAL_IP/v1/decodeJWT" -H "Authorization: Bearer eyJ1c2VySWQiOiJiMDhmODZhZi0zNWRhLTQ4ZjItOGZhYi1jZWYzOTA0NjYwYmQifQ.-xN_h82PHVTCMA9vdoHrcZxH-x5mb11y1537t3rGzcM"
    

    Where $EXTERNAL_IP is the IP address of the external load balancer.
    This IP address is exposed to the internet. For more information, see
    Configure routing.

    Close examination of the JWT shows that it has the format payload.signature which is invalid. The expected format of the JWT is header.payload.signature. As a result, the Decode JWT policy fails with the error :

    "faultstring": "Failed to Decode Token: policy({0})"
    

Resolution

Ensure that the JWT passed to the Decode JWT policy contains all three elements, is correctly formatted and is decodable.

To correct the example shown above, you can pass in a valid JWT with the format header.payload.signature. This can be done by making the API call using the cURL command as follows:

curl -v "http://$EXTERNAL_IP/v1/decodeJWT" -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiJiMDhmODZhZi0zNWRhLTQ4ZjItOGZhYi1jZWYzOTA0NjYwYmQifQ.-xN_h82PHVTCMA9vdoHrcZxH-x5mb11y1537t3rGzcM"

Where $EXTERNAL_IP is the IP address of the external load balancer.
This IP address is exposed to the internet. For more information, see
Configure routing.

InvalidToken

Error code

steps.jwt.InvalidToken

Error response body

{
  "fault": {
    "faultstring": "Invalid token: policy({0})",
    "detail": {
      "errorcode": "steps.jwt.InvalidToken"
     }
  }
}

Cause

This error occurs if the flow variable specified in the <Source> element of the Decode JWT policy is:

  • out of scope (not available in the specific flow where the policy is being executed) or
  • can’t be resolved (is not defined)

Diagnosis

  1. Identify the variable specified in the <Source> element of the Decode JWT policy. This variable should contain the JWT.

    Here’s a sample Decode JWT policy:

    <DecodeJWT name="JWT-Decode-HS256">
        <DisplayName>JWT Verify HS256</DisplayName>
        <Source>request.header.authorization</Source>
        <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
    </DecodeJWT>
    

    In the example above, the Authorization request header should contain the JWT.

  2. Determine if the variable identified in Step 1 is defined and available in the flow in which the Decode JWT policy is executed.

  3. If the variable is either:

    • out of scope (not available in the specific flow where the policy is being executed) or
    • can’t be resolved (is not defined)

    then that’s the cause for the error.

    In the example API request below, the JWT is not passed in the authorization request header by the user.

    curl -v "http://$EXTERNAL_IP/v1/decodeJWT"
    

Where $EXTERNAL_IP is the IP address of the external load balancer.
This IP address is exposed to the internet. For more information, see
Configure routing.

Because the authorization request header is not passed, the Decode JWT policy fails with the error:

```
"faultstring": "Invalid token: policy({0})"
```

Resolution

Ensure that the variable referenced in the <Source> element of the Decode JWT policy is defined, contains a valid (decodable) JWT and is available in the specific flow where the Decode JWT policy is being executed.

To correct the example shown above, you can pass a valid JWT in the request authorization header. This can be done by making the API call using the cURL command as follows:

curl -v "http://$EXTERNAL_IP/v1/decodeJWT" -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiJiMDhmODZhZi0zNWRhLTQ4ZjItOGZhYi1jZWYzOTA0NjYwYmQifQ.-xN_h82PHVTCMA9vdoHrcZxH-x5mb11y1537t3rGzcM"

Where $EXTERNAL_IP is the IP address of the external load balancer.
This IP address is exposed to the internet. For more information, see
Configure routing.


You’re viewing Apigee Edge documentation.
View
Apigee X documentation.

FailedToDecode

Error code

steps.jwt.FailedToDecode

Error response body

{
  "fault": {
    "faultstring": "Failed to Decode Token: policy({0})",
    "detail": {
       "errorcode": "steps.jwt.FailedToDecode"
     }
  }
}

Cause

This error occurs if the JSON Web Token (JWT) specified in the <Source> element of the Decode JWT policy is malformed, invalid or otherwise not decodable.

A properly structured JWT should contain a header, payload and signature in the following format: header.payload.signature. If the JWT passed to the DecodeJWT policy is missing a component part, then you will get the error. For example, if the JWT has only payload.signature, but is missing its header, the error will occur.

Diagnosis

  1. Identify the variable specified in the <Source> element of the Decode JWT policy. This variable should contain the JWT.

    Here’s a sample Decode JWT policy:

    <DecodeJWT name="JWT-Decode-HS256">
        <DisplayName>JWT Verify HS256</DisplayName>
        <Source>request.header.authorization</Source>
        <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
    </DecodeJWT>
    

    In the above example, the JWT should be contained in the Authorization request header.

  2. Examine the variable identified in Step 1 and check to see if the JWT it contains is valid. If the input JWT is not valid, then that’s the cause for the error.

    In the example API request below, the input JWT is passed in the Authorization request header:

    curl -v "http://<org>-<env>.apigee.net/v1/decodeJWT" -H "Authorization: Bearer eyJ1c2VySWQiOiJiMDhmODZhZi0zNWRhLTQ4ZjItOGZhYi1jZWYzOTA0NjYwYmQifQ.-xN_h82PHVTCMA9vdoHrcZxH-x5mb11y1537t3rGzcM"
    

    Close examination of the JWT shows that it has the format payload.signature which is invalid. The expected format of the JWT is header.payload.signature. As a result, the Decode JWT policy fails with the error :

    "faultstring": "Failed to Decode Token: policy({0})"
    

Resolution

Ensure that the JWT passed to the Decode JWT policy contains all three elements, is correctly formatted and is decodable.

To correct the example shown above, you can pass in a valid JWT with the format header.payload.signature. This can be done by making the API call using the cURL command as follows:

curl -v "http://<org>-<env>.apigee.net/v1/decodeJWT" -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiJiMDhmODZhZi0zNWRhLTQ4ZjItOGZhYi1jZWYzOTA0NjYwYmQifQ.-xN_h82PHVTCMA9vdoHrcZxH-x5mb11y1537t3rGzcM"

InvalidToken

Error code

steps.jwt.InvalidToken

Error response body

{
  "fault": {
    "faultstring": "Invalid token: policy({0})",
    "detail": {
      "errorcode": "steps.jwt.InvalidToken"
     }
  }
}

Cause

This error occurs if the flow variable specified in the <Source> element of the Decode JWT policy is:

  • out of scope (not available in the specific flow where the policy is being executed) or
  • can’t be resolved (is not defined)

Diagnosis

  1. Identify the variable specified in the <Source> element of the Decode JWT policy. This variable should contain the JWT.

    Here’s a sample Decode JWT policy:

    <DecodeJWT name="JWT-Decode-HS256">
        <DisplayName>JWT Verify HS256</DisplayName>
        <Source>request.header.authorization</Source>
        <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
    </DecodeJWT>
    

    In the example above, the Authorization request header should contain the JWT.

  2. Determine if the variable identified in Step 1 is defined and available in the flow in which the Decode JWT policy is executed.

  3. If the variable is either:

    • out of scope (not available in the specific flow where the policy is being executed) or
    • can’t be resolved (is not defined)

    then that’s the cause for the error.

    In the example API request below, the JWT is not passed in the authorization request header by the user.

    curl -v "http://<org>-<env>.apigee.net/v1/decodeJWT"
    

    Because the authorization request header is not passed, the Decode JWT policy fails with the error:

    "faultstring": "Invalid token: policy({0})"
    

Resolution

Ensure that the variable referenced in the <Source> element of the Decode JWT policy is defined, contains a valid (decodable) JWT and is available in the specific flow where the Decode JWT policy is being executed.

To correct the example shown above, you can pass a valid JWT in the request authorization header. This can be done by making the API call using the cURL command as follows:

curl -v "http://<org>-<env>.apigee.net/v1/decodeJWT" -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiJiMDhmODZhZi0zNWRhLTQ4ZjItOGZhYi1jZWYzOTA0NjYwYmQifQ.-xN_h82PHVTCMA9vdoHrcZxH-x5mb11y1537t3rGzcM"

The following are 30
code examples of jwt.DecodeError().
You can vote up the ones you like or vote down the ones you don’t like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module

jwt
, or try the search function

.

Example #1

def validate(self, token):
        public_key = self._get_public_key(token)
        if not public_key:
            raise TokenError("No key found for this token")

        try:
            jwt_data = jwt.decode(
                token,
                public_key,
                audience=self.audience,
                issuer=self.pool_url,
                algorithms=["RS256"],
            )
        except (jwt.InvalidTokenError, jwt.ExpiredSignature, jwt.DecodeError) as exc:
            raise TokenError(str(exc))
        return jwt_data 

Example #2

def fetch_token_header(token):
    """
    Fetch the header out of the JWT token.

    :param token:
    :return: :raise jwt.DecodeError:
    """
    token = token.encode("utf-8")
    try:
        signing_input, crypto_segment = token.rsplit(b".", 1)
        header_segment, payload_segment = signing_input.split(b".", 1)
    except ValueError:
        raise jwt.DecodeError("Not enough segments")

    try:
        return json.loads(jwt.utils.base64url_decode(header_segment).decode("utf-8"))
    except TypeError as e:
        current_app.logger.exception(e)
        raise jwt.DecodeError("Invalid header padding") 

Example #3

def authenticate(self, request):
        """
        Returns a two-tuple of `User` and token if a valid signature has been
        supplied using JWT-based authentication.  Otherwise returns `None`.
        """
        jwt_value = self._get_jwt_value(request)
        if jwt_value is None:
            return None

        try:
            payload = decode_jwt(jwt_value)
        except jwt.ExpiredSignatureError:
            msg = 'Signature has expired.'
            raise exceptions.AuthenticationFailed(msg)
        except jwt.DecodeError:
            msg = 'Error decoding signature.'
            raise exceptions.AuthenticationFailed(msg)
        except jwt.InvalidTokenError:
            raise exceptions.AuthenticationFailed()

        self._add_session_details(request, payload)

        user = self.authenticate_credentials(payload)
        return user, JwtToken(payload) 

Example #4

def process_request(self, request):
        if request.META.get('HTTP_AUTHORIZATION'):
            token = (request.META.get('HTTP_AUTHORIZATION').split(' '))[1]
            try:
                payload = jwt_decode_handler(token)
                user_id =  jwt_get_user_id_from_payload_handler(payload)
                if not user_id:
                    return JsonResponse({"message": "用户不存在!" , "errorCode": 2, "data": {}})
                now_user = User.objects.values('id', 'is_freeze').filter(id=user_id).first()
                if not now_user:
                    return JsonResponse({"message": "用户不存在!" , "errorCode": 2, "data": {}})
                if now_user.get('is_freeze'):
                    return JsonResponse({"message": "账户被冻结!", "errorCode": 2, "data": {}})
            except jwt.ExpiredSignature:
                return JsonResponse({"message": 'Token过期' , "errorCode": 2, "data": {}})
            except jwt.DecodeError:
                return JsonResponse({"message": 'Token不合法' , "errorCode": 2, "data": {}})
            except jwt.InvalidTokenError as e:
                return JsonResponse({"message": "出现了无法预料的view视图错误:%s" % e, "errorCode": 1, "data": {}}) 

Example #5

def authenticate(self, request):
        """
        Returns a two-tuple of `User` and token if a valid signature has been
        supplied using JWT-based authentication.  Otherwise returns `None`.
        """
        jwt_value = self.get_jwt_value(request)
        if jwt_value is None:
            return None

        try:
            payload = jwt_decode_handler(jwt_value)
        except jwt.ExpiredSignature:
            msg = 'Token过期'
            raise exceptions.AuthenticationFailed({"message": msg,"errorCode":1,"data":{}})
        except jwt.DecodeError:
            msg = 'Token不合法'
            raise exceptions.AuthenticationFailed({"message": msg,"errorCode":1,"data":{}})
        except jwt.InvalidTokenError:
            raise exceptions.AuthenticationFailed()

        user = self.authenticate_credentials(payload)
        return user, jwt_value 

Example #6

def login_req(f):
    @wraps(f)
    def decorated_func(*args, **kwargs):
        if not request.headers.get('Authorization'):
            return jsonify(message='Please login'), 401
        try:
            payload = _parse_token_from_header(request)
            g.user_id = payload['sub']
            return f(*args, **kwargs)
        except DecodeError:
            return jsonify(message='Your session is invalid'), 401
        except ExpiredSignature:
            return jsonify(message='
Your session has expired. Please login again.'), 401

    return decorated_func 

Example #7

def authenticate(self, request):
        """
        Returns a two-tuple of `User` and token if a valid signature has been
        supplied using JWT-based authentication.  Otherwise returns `None`.
        """
        jwt_value = self.get_jwt_value(request)
        if jwt_value is None:
            return None

        try:
            payload = jwt_decode_handler(jwt_value)
        except jwt.ExpiredSignature:
            msg = _('Signature has expired.')
            raise exceptions.AuthenticationFailed(msg)
        except jwt.DecodeError:
            msg = _('Error decoding signature.')
            raise exceptions.AuthenticationFailed(msg)
        except jwt.InvalidTokenError:
            raise exceptions.AuthenticationFailed()

        user = self.authenticate_credentials(payload)

        return (user, payload) 

Example #8

def _get_public_key(self, token):
        try:
            headers = jwt.get_unverified_header(token)
        except jwt.DecodeError as exc:
            raise TokenError(str(exc))

        if getattr(settings, "COGNITO_PUBLIC_KEYS_CACHING_ENABLED", False):
            cache_key = "django_cognito_jwt:%s" % headers["kid"]
            jwk_data = cache.get(cache_key)

            if not jwk_data:
                jwk_data = self._json_web_keys.get(headers["kid"])
                timeout = getattr(settings, "COGNITO_PUBLIC_KEYS_CACHING_TIMEOUT", 300)
                cache.set(cache_key, jwk_data, timeout=timeout)
        else:
            jwk_data = self._json_web_keys.get(headers["kid"])

        if jwk_data:
            return RSAAlgorithm.from_jwk(jwk_data) 

Example #9

def update_token(self, token: str) -> None:
        """
        Replace this connection's API token with a new one.

        Parameters
        ----------
        token : str
            JSON Web Token for this API server
        """
        try:
            self.user = jwt.decode(token, verify=False)["identity"]
        except jwt.DecodeError:
            raise FlowclientConnectionError(f"Unable to decode token: '{token}'")
        except KeyError:
            raise FlowclientConnectionError(f"Token does not contain user identity.")
        self.token = token
        self.session.headers["Authorization"] = f"Bearer {self.token}" 

Example #10

def get_certificate(self, kid):
        # retrieve keys from jwks_url
        resp = self.request(self.jwks_url(), method='GET')
        resp.raise_for_status()

        # find the proper key for the kid
        for key in resp.json()['keys']:
            if key['kid'] == kid:
                x5c = key['x5c'][0]
                break
        else:
            raise DecodeError('Cannot find kid={}'.format(kid))

        certificate = '-----BEGIN CERTIFICATE-----n' 
                      '{}n' 
                      '-----END CERTIFICATE-----'.format(x5c)

        return load_pem_x509_certificate(certificate.encode(),
                                         default_backend()) 

Example #11

def user_data(self, access_token, *args, **kwargs):
        response = kwargs.get('response')
        id_token = response.get('id_token')

        # decode the JWT header as JSON dict
        jwt_header = json.loads(
            base64.b64decode(id_token.split('.', 1)[0]).decode()
        )

        # get key id and algorithm
        key_id = jwt_header['kid']
        algorithm = jwt_header['alg']

        try:
            # retrieve certificate for key_id
            certificate = self.get_certificate(key_id)

            return jwt_decode(
                id_token,
                key=certificate.public_key(),
                algorithms=algorithm,
                audience=self.setting('SOCIAL_AUTH_AZUREAD_OAUTH2_KEY')
            )
        except (DecodeError, ExpiredSignature) as error:
            raise AuthTokenError(self, error) 

Example #12

def user_data(self, access_token, *args, **kwargs):
        response = kwargs.get('response')

        id_token = response.get('id_token')
        if six.PY2:
            # str() to fix a bug in Python's base64
            # https://stackoverflow.com/a/2230623/161278
            id_token = str(id_token)

        jwt_header_json = base64url_decode(id_token.split('.')[0])
        jwt_header = json.loads(jwt_header_json.decode('ascii'))

        # `kid` is short for key id
        key = self.get_public_key(jwt_header['kid'])

        try:
            return jwt_decode(
                id_token,
                key=key,
                algorithms=jwt_header['alg'],
                audience=self.setting('KEY'),
                leeway=self.setting('JWT_LEEWAY', default=0),
            )
        except (DecodeError, ExpiredSignature) as error:
            raise AuthTokenError(self, error) 

Example #13

def login_required(method):
    @functools.wraps(method)
    def wrapper(self):
        header = request.headers.get('Authorization')
        _, token = header.split()
        try:
            decoded = jwt.decode(token, app.config['KEY'], algorithms='HS256')
        except jwt.DecodeError:
            abort(400, message='Token is not valid.')
        except jwt.ExpiredSignatureError:
            abort(400, message='Token is expired.')
        email = decoded['email']
        if db.users.find({'email': email}).count() == 0:
            abort(400, message='User is not found.')
        user = db.users.find_one({'email': email})
        return method(self, user)
    return wrapper 

Example #14

def verify(self, token, verifying_key):
        # grab the token parts
        token_parts = self._unpack(token)
        header, payload, raw_signature, signing_input = token_parts
        # load the verifying key
        verifying_key = load_verifying_key(verifying_key, self.crypto_backend)
        # convert the raw_signature to DER format
        der_signature = raw_to_der_signature(
            raw_signature, verifying_key.curve)
        # initialize the verifier
        verifier = self._get_verifier(verifying_key, der_signature)
        verifier.update(signing_input)
        # check to see whether the signature is valid
        try:
            verifier.verify()
        except InvalidSignature:
            # raise DecodeError('Signature verification failed')
            return False
        return True 

Example #15

def authenticate(cls, jwt_token):
        """
        Validates if JWT Token still stands True.
        :param jwt_token: JWT Token issued by generate_token method
        :return: A dict containing status and payload on success
        """

        if jwt_token:
            try:
                payload = jwt.decode(jwt_token, cls.app_secret)
            except (jwt.DecodeError, jwt.ExpiredSignatureError) as e:
                cls.token_authenticator_logger.exception(
                    '[JWT Manager]: Authentication failed due to : {}'.format(str(e)))
                return {
                    'status': False,
                    'message': 'Token invalid {}'.format(str(e)),
                    'encode_value': None
                }
            cls.token_authenticator_logger.info('[JWT Manager]: Authentication succeded.')
            return {
                'status': True,
                'message': 'Token valid',
                'encode_value': payload['encode_value']
            } 

Example #16

def __check_auth(self, view):
        headers = {x[0]: x[1] for x in request.headers}
        if 'Authorization' in headers:
            try:
                token = jwt.decode(
                    headers['Authorization'],
                    get_jwt_key_data()
                )

                if token['auth_system'] != current_app.active_auth_system.name:
                    self.log.error('Token is from another auth_system ({}) than the current one ({})'.format(
                        token['auth_system'],
                        current_app.active_auth_system.name
                    ))

                    return view.make_unauth_response()

                if has_access(session['user'], self.role):
                    return

                self.log.error('User {} attempted to access page {} without permissions'.format(
                    session['user'].username,
                    request.path
                ))
                return view.make_unauth_response()

            except (jwt.DecodeError, jwt.ExpiredSignatureError) as ex:
                session.clear()
                view.log.info('Failed to decode signature or it had expired: {0}'.format(ex))
                return view.make_unauth_response()

        session.clear()
        view.log.info('Failed to detect Authorization header')
        return view.make_unauth_response() 

Example #17

def api_key_required(request=None, action=None):
    """
    This is a decorator for check_user_pass and check_serial_pass.
    It checks, if a policy scope=auth, action=apikeyrequired is set.
    If so, the validate request will only performed, if a JWT token is passed
    with role=validate.
    """
    user_object = request.User

    # Get the policies
    action = Match.user(g, scope=SCOPE.AUTHZ, action=ACTION.APIKEY, user_object=user_object).policies()
    # Do we have a policy?
    if action:
        # check if we were passed a correct JWT
        # Get the Authorization token from the header
        auth_token = request.headers.get('PI-Authorization')
        if not auth_token:
            auth_token = request.headers.get('Authorization')
        try:
            r = jwt.decode(auth_token, current_app.secret_key, algorithms=['HS256'])
            g.logged_in_user = {"username": r.get("username", ""),
                                "realm": r.get("realm", ""),
                                "role": r.get("role", "")}
        except (AttributeError, jwt.DecodeError):
            # PyJWT 1.3.0 raises AttributeError, PyJWT 1.6.4 raises DecodeError.
            raise PolicyError("No valid API key was passed.")

        role = g.logged_in_user.get("role")
        if role != ROLE.VALIDATE:
            raise PolicyError("A correct JWT was passed, but it was no API "
                              "key.")

    # If everything went fine, we call the original function
    return True 

Example #18

def _decode_header(auth_header, client_id, client_secret):
    """
    Takes the header and tries to return an active token and decoded
    payload.
    :param auth_header:
    :param client_id:
    :param client_secret:
    :return: (token, profile)
    """
    try:
        token = auth_header.split()[1]
        payload = jwt.decode(
            token,
            client_secret,
            audience=client_id)
    except jwt.ExpiredSignature:
        raise exceptions.NotAuthorizedException(
            'Token has expired, please log in again.')
    # is valid client
    except jwt.InvalidAudienceError:
        message = 'Incorrect audience, expected: {}'.format(
            client_id)
        raise exceptions.NotAuthorizedException(message)
    # is valid token
    except jwt.DecodeError:
        raise exceptions.NotAuthorizedException(
            'Token signature could not be validated.')
    except Exception as e:
        raise exceptions.NotAuthorizedException(
            'Token signature was malformed. {}'.format(e.message))
    return token, payload 

Example #19

def API_verification(auth_token):

        try:
            Decoded_Token = jwt.decode(auth_token, API_Secret, algorithm='HS256')
            User_ID = int(Decoded_Token['id'])
            Cursor.execute('SELECT * FROM users WHERE user_id = %s', (User_ID,))
            User_Details = Cursor.fetchone()

            if auth_token == User_Details[5]:

                if not User_Details[3]:
                    return {"Token": True, "Admin": User_Details[4], "Username": User_Details[1], "Message": "Token verification successful."}

                else:
                    return {"Token": False, "Admin": False, "Message": "Token blocked."}

            else:
                return {"Token": False, "Admin": False, "Message": "Invalid token."}

        except jwt.ExpiredSignatureError:
            return {"Token": False, "Admin": False, "Message": "Token expired."}

        except jwt.DecodeError:
            return {"Token": False, "Admin": False, "Message": "Failed to decode token."}

        except jwt.InvalidTokenError:
            return {"Token": False, "Admin": False, "Message": "Invalid token."} 

Example #20

def validate_id_token(id_token, client_id, jwks_url):
    """
    Ensures that the token we receive is valid.

    :param id_token:
    :param client_id:
    :param jwks_url:
    :return:
    """
    # fetch token public key
    header_data = fetch_token_header(id_token)

    # retrieve the key material as specified by the token header
    r = requests.get(jwks_url)
    for key in r.json()["keys"]:
        if key["kid"] == header_data["kid"]:
            secret = get_rsa_public_key(key["n"], key["e"])
            algo = header_data["alg"]
            break
    else:
        return dict(message="Key not found"), 401

    # validate your token based on the key it was signed with
    try:
        jwt.decode(
            id_token, secret.decode("utf-8"), algorithms=[algo], audience=client_id
        )
    except jwt.DecodeError:
        return dict(message="Token is invalid"), 401
    except jwt.ExpiredSignatureError:
        return dict(message="Token has expired"), 401
    except jwt.InvalidTokenError:
        return dict(message="Token is invalid"), 401 

Example #21

def get_payload(token, context=None):
    try:
        payload = jwt_settings.JWT_DECODE_HANDLER(token, context)
    except jwt.ExpiredSignature:
        raise exceptions.JSONWebTokenExpired()
    except jwt.DecodeError:
        raise exceptions.JSONWebTokenError(_('Error decoding signature'))
    except jwt.InvalidTokenError:
        raise exceptions.JSONWebTokenError(_('Invalid token'))
    return payload 

Example #22

def decode_token(self, token):
    try:
      decoded = jwt.decode(token, self.config['JWT_SECRET_KEY'],
          algorithms=[self.config['JWT_ALGORITHM']], leeway=self.config.get('JWT_LEEWAY', 0))
    except jwt.ExpiredSignatureError:
      raise werkzeug.exceptions.Unauthorized("JWT Error: Token is expired.")
    except jwt.DecodeError:
      raise werkzeug.exceptions.Unauthorized("JWT Error: Token could not be decoded.")
    except jwt.InvalidTokenError:
      raise werkzeug.exceptions.Unauthorized("JWT Error: Token is invalid.")
    return decoded 

Example #23

def _decode(self, token):
        try:
            return jwt.decode(token, algorithms=['RS256'], verify=False)
        except jwt.DecodeError:
            message = "Token can't be decoded because of wrong format."
            self._unauthorized(message) 

Example #24

def _check_payload(self, token):
        # Check payload valid (based off of JSONWebTokenAuthentication,
        # may want to refactor)
        try:
            payload = jwt_decode_handler(token)
        except jwt.ExpiredSignature:
            msg = _('Signature has expired.')
            raise serializers.ValidationError(msg)
        except jwt.DecodeError:
            msg = _('Error decoding signature.')
            raise serializers.ValidationError(msg)

        return payload 

Example #25

def get_user(self, token):
        """Gets the user from credentials object. None if no credentials.
        Can raise jwt.ExpiredSignature and jwt.DecodeError"""
        profile = self.get_profile(token)
        if not profile:
            return None
        username = profile.get("user", None)
        user = self.server_store.read_user(username)
        # Timestamp must match with the stored in user, if not,
        # this token is not valid (password has been changed)
        password_timestamp = profile["password_timestamp"]
        if password_timestamp != user.password_timestamp:
            logger.debug("Timestamp doesn't match!")
            raise jwt.DecodeError("Timestamp doesn't match!")
        return username 

Example #26

def test_invalid_token(self):
        '''Obtain a valid token and then change password. Token must be invalid'''
        brl_user, token_1 = self.user_service.authenticate(self.brl_user, self.plain_password)
        # Check the token is valid
        manager = JWTCredentialsManagerFactory.new(self.store)
        brl_user_test = manager.get_user(token_1)
        self.assertEqual(brl_user, brl_user_test)
        sleep(0.1)  # Sleep a moment and change the password

        # Now change password and re-check old token
        self.user_service.change_password(self.brl_user, self.plain_password, "Newp@sW0rd")

        # Check the token is invalid (can't authenticate)
        self.assertRaises(DecodeError, manager.get_user, token_1) 

Example #27

def validate_access_token(self, access_token):
        for idx, key in enumerate(provider_config.signing_keys):
            try:
                # Explicitly define the verification option.
                # The list below is the default the jwt module uses.
                # Explicit is better then implicit and it protects against
                # changes in the defaults the jwt module uses.
                options = {
                    'verify_signature': True,
                    'verify_exp': True,
                    'verify_nbf': True,
                    'verify_iat': True,
                    'verify_aud': True,
                    'verify_iss': True,
                    'require_exp': False,
                    'require_iat': False,
                    'require_nbf': False
                }
                # Validate token and return claims
                return jwt.decode(
                    access_token,
                    key=key,
                    algorithms=['RS256', 'RS384', 'RS512'],
                    verify=True,
                    audience=settings.AUDIENCE,
                    issuer=provider_config.issuer,
                    options=options,
                )
            except jwt.ExpiredSignature as error:
                logger.info("Signature has expired: %s", error)
                raise PermissionDenied
            except jwt.DecodeError as error:
                # If it's not the last certificate in the list, skip to the next one
                if idx < len(provider_config.signing_keys) - 1:
                    continue
                else:
                    logger.info('Error decoding signature: %s', error)
                    raise PermissionDenied
            except jwt.InvalidTokenError as error:
                logger.info(str(error))
                raise PermissionDenied 

Example #28

def assertValidIDToken(self, id_token, secret, audience):
        try:
            jwt.decode(id_token, secret, audience=audience)
        except jwt.DecodeError:
            assert False 

Example #29

def get_object(self, view_name, view_args, view_kwargs):
        try:
            transaction_uuid = jwt.decode(view_kwargs['token'],
                                          settings.PAYMENT_METHOD_SECRET)['transaction']
            return self.queryset.get(uuid=transaction_uuid)
        except (jwt.ExpiredSignatureError, jwt.DecodeError, jwt.InvalidTokenError):
            return None 

Example #30

def validate_token(self, token=''):
        """Validate JWT token.

        Args:
            token (str): A Json Web token string.

        Returns:
            The decrypted token data (dict)

        Raises:
            JWTProviderError, if no token is provided, or if it is expired.
        """
        if not token:
            logger.debug("Forbidden access")
            raise JWTForbiddenError('Cannot access this resource!')

        try:
            decoded = jwt.decode(
                token.split(" ", 1).pop(),
                self.secret,
                algorithms=self.algorithm
            )

            logger.debug("Token validation passed: {}".format(token))

            user_uid = decoded.get('sub')

            if not user_uid:  # pragma: no cover
                raise JWTUnauthorizedError('Invalid User token')

            user = self.backend.get_user(json.loads(base64.b64decode(user_uid).decode('utf-8')))

            if user:
                return user

            raise JWTUnauthorizedError('Invalid User token')

        except (jwt.DecodeError, jwt.ExpiredSignatureError) as e:
            logger.debug("{}: {}".format(e.args[0], token))
            raise JWTUnauthorizedError("Invalid auth token provided.") 

Понравилась статья? Поделить с друзьями:
  • Jvm dll error minecraft
  • Jurists help those people who to commit an error already перевод
  • Jvm dll error at hooking api loadstringa dumping first 32 bytes
  • Jurists help those people who have committed an error already
  • Jvm cfg ошибка