Set up JWT token in tyk gateway

I’m using Tyk gateway community version and I’m trying to set up JWT token but it is not working as expected and is giving following error response when the api end point is called.
Thanks in advance.
Error response:
{
“error”: “Key not authorized:token contains an invalid number of segments”
}
My tyk.conf is as follows :
apiVersion: v1
data:
tyk.conf: |
{
“listen_port”: 8080,
“secret”: “352d20ee67be67f6340b4c0605b044b7”,
“template_path”: “/opt/tyk-gateway/templates”,
“tyk_js_path”: “/opt/tyk-gateway/js/tyk.js”,
“middleware_path”: “/opt/tyk-gateway/middleware”,
“use_db_app_configs”: false,
“app_path”: “/opt/tyk-gateway/apps/”,
“storage”: {
“type”: “redis”,
“host”: “localhost”,
“port”: 30072,
“username”: “”,
“password”: “”,
“database”: 0,
“optimisation_max_idle”: 2000,
“optimisation_max_active”: 4000
},
“enable_analytics”: false,
“analytics_config”: {
“type”: “csv”,
“csv_dir”: “/tmp”,
“mongo_url”: “”,
“mongo_db_name”: “”,
“mongo_collection”: “”,
“purge_delay”: -1,
“ignored_ips”: []
},
“health_check”: {
“enable_health_checks”: true,
“health_check_value_timeouts”: 60
},
“optimisations_use_async_session_write”: true,
“enable_non_transactional_rate_limiter”: true,
“enable_sentinel_rate_limiter”: false,
“enable_redis_rolling_limiter”: false,
“allow_master_keys”: false,
“policies”: {
“policy_source”: “file”,
“policy_record_name”: “/opt/tyk-gateway/policies/policies.json”
},
“hash_keys”: true,
“close_connections”: false,
“http_server_options”: {
“enable_websockets”: true
},
“allow_insecure_configs”: true,
“coprocess_options”: {
“enable_coprocess”: true,
“coprocess_grpc_server”: “”,
“coprocess_grpc_api_key”: “”,
“coprocess_python_path”: “”
},
“enable_bundle_downloader”: true,
“bundle_base_url”: “”,
“global_session_lifetime”: 100,
“force_global_session_lifetime”: false,
“max_idle_connections_per_host”: 500
}
“auth”: {
“auth_header_name”: “Authorization”,
“use_param”: false,
“jwt_secret”: “tyk123”,
“enable_jwt”: true,
“jwt_default_issuer”: “”,
“jwt_default_audience”: “”,
“jwt_identity_base_field”: “sub”,
“jwt_client_base_field”: “aud”,
“jwt_policy_field_name”: “pol”,
“jwt_signing_method”: “H256”,
“jwt_default_signing_key”: “LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0NCk1JR2ZNQTBHQ1NxR1NJYjNEUUVCQVFVQUE0R05BRENCaVFLQmdRRFdtakFiUEV3ZTFRdm44RHdHTnhTdlE1c1gNCnIyWmxNMUwvaCtTczQ0WTNHeHhYY3dKc0RlelREbnhzNFdrekpIZHNPeWh3eDRLNGVnTDBGOEVaZHpBUlBtT28NCkFqWEpEOG8vdlB0V202dFIzRVdkVkNQaTBjZTE2ekZhVUUxRkVZRGZNbDFXUHFtOG9Na2Rsd2tFbG1DT1ZJR2INClFIQjJyQ2R4dFN2ZlZpNk9PUUlEQVFBQg0KLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0t”,
“jwt_policy_prefix”: “”
}
kind: ConfigMap
metadata:
name: tyk-gateway-conf

My partial log is
time=“Aug 02 06:55:12” level=info msg=“Attempted JWT access with non-existent key.” api_id=5 api_name=“Test API5” mw=JWTMiddleware org_id=1 origin=10.244.0.1 path=“/api/mail”
time=“Aug 02 06:55:12” level=error msg=“JWT validation error” api_id=5 api_name=“Test API5” error=“token contains an invalid number of segments” mw=JWTMiddleware org_id=1 origin=10.244.0.1 path=“/api/mail”

Hi @A.M.Saranya,

Welcome to the community! :partying_face:

Sorry for the trouble with this.

From the error and the logs, it looks like the token may be malformed. Are you able to verify the validity of the token on jwt.io?

Are you including ‘Bearer’ in the authorization header when you call the API?
curl http://<tyk-gateway>/api/mail -H "Authorization: Bearer <JWT>"

I don’t think you have, but have you mixed your API definition with your Gateway config file? These should be separate files.

Your partial API definition appears to have some issues too. For instance, I’m not sure “jwt_secret” is a valid field… or is “jwt_default_signing_key”.
Here’s what a valid API definition might look like:

{
    "id": "5",
    "name": "Test API5",
    "slug": "testapi5",
    "listen_port": 0,
    "protocol": "",
    "api_id": "5",
    "org_id": "64ca4c545cf4060001966aef",
    "auth_configs": {
        "jwt": {
            "name": "",
            "use_param": false,
            "param_name": "",
            "use_cookie": false,
            "cookie_name": "",
            "disable_header": false,
            "auth_header_name": "Authorization",
            "use_certificate": false,
            "validate_signature": false,
            "signature": {
                "algorithm": "",
                "header": "",
                "use_param": false,
                "param_name": "",
                "secret": "",
                "allowed_clock_skew": 0,
                "error_code": 0,
                "error_message": ""
            }
        }
    },
    "enable_jwt": true,
    "jwt_signing_method": "hmac",
    "jwt_source": "LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlJQklqQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FROEFNSUlCQ2dLQ0FRRUE0YkNQY01hSWs0SnhFNGtGWmx4dApEKy9VbHAweU92MU1jRkQzN3pmN0VJMGFJaHc0WGpVZUZ6M0VwV2ZQdGJWNGVlbkxQamFSTmlOVlppbzQvdUk2CllhS3Q4VUE3UGJRNFc2SGRSbkU2WExaOEpxWVhkY0h6eDFNbHAzVEVPRlBsWHBRYU5PM1RmdWlYTGNTN3p5NlUKaGMvVGdkZ1RWUWRiYUZvWEdUK05KOXNKK3B1QmUvRzE0NGVNZkRXa093c3Y1MVJRNHdsUGwxbFgydG9qMmJBbApNblRkcytrTk1BdlhweG1jQUFBdWxsWi9vUE1tNDBIYzVXNnU5RUlnOHFIeFpzVW1YSzM5NmRBT3JkM3ZrMUxPCnBlS1Q4d2VoWmt6azJaUng2RWhuelplOG5KWnEyaWJBOURvVldsTldtV2Y4S0RYaUUzdFU1ZjQwNTZxRWc3dm0KcndJREFRQUIKLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0t",
    "jwt_identity_base_field": "sub",
    "jwt_client_base_field": "",
    "jwt_policy_field_name": "pol",
    "jwt_default_policies": [
        "64cb9e6daad1a80001567698"
    ],
    "jwt_issued_at_validation_skew": 0,
    "jwt_expires_at_validation_skew": 0,
    "jwt_not_before_validation_skew": 0,
    "jwt_skip_kid": false,
    "scopes": {
        "jwt": {
            "scope_claim_name": "",
            "scope_to_policy": {}
        },
        "oidc": {
            "scope_claim_name": "",
            "scope_to_policy": {}
        }
    },
    "jwt_scope_to_policy_mapping": {},
    "jwt_scope_claim_name": "",
    "enable_signature_checking": false,
    "hmac_allowed_clock_skew": -1,
    "hmac_allowed_algorithms": [],
    "request_signing": {
        "is_enabled": false,
        "secret": "",
        "key_id": "",
        "algorithm": "",
        "header_list": [],
        "certificate_id": "",
        "signature_header": ""
    },
    "base_identity_provided_by": "",
    "version_data": {
        "not_versioned": true,
        "default_version": "",
        "versions": {
            "Default": {
                "name": "Default",
                "expires": "",
                "paths": {
                    "ignored": [],
                    "white_list": [],
                    "black_list": []
                },
                "use_extended_paths": true,
                "extended_paths": {}
            }
        }
    },
    "proxy": {
        "preserve_host_header": false,
        "listen_path": "/api1/",
        "target_url": "http://httpbin.org/",
        "disable_strip_slash": true,
        "strip_listen_path": true
    },
    "session_lifetime_respects_key_expiration": false,
    "session_lifetime": 0,
    "active": true,
    "internal": false,
    "allowed_ips": [],
    "blacklisted_ips": [],
    "expire_analytics_after": 0,
    "response_processors": [],
    "config_data": {},
    "tag_headers": []
}

Generally please review our doc on JWT.

Please let us know if any of the suggestions help you resolve the issue… or not.

  1. I’m also using same api definition and my policies.json is
    {
    “1”: {
    “rate”: 1000,
    “id”: “1”,
    “per”: 1,
    “quota_max”: 100,
    “quota_renewal_rate”: 60,
    “access_rights”: {
    “3”: {
    “api_name”: “Test API5”,
    “api_id”: “5”,
    “versions”: [
    “Default”
    ]
    }
    },
    “org_id”: “64ca4c545cf4060001966aef”,
    “hmac_enabled”: false
    }
    }
  2. yes. to call an api am also including ‘Bearer’ in the authorization header.still am facing same error.

Hi,

Have you updated your API definition to look like what I shared in the response? Please share the updated API definition.

Also, please confirm the Gateway version and share the logs as well.

my api definition file is
{
“name”: “JWT-TEST”,
“slug”: “jwt-test”,
“api_id”: “3”,
“org_id”: “test-org”,
“use_keyless”: false,
“use_oauth2”: false,
“use_openid”: false,
“openid_options”: {
“providers”: [],
“segregate_by_client”: false
},
“oauth_meta”: {
“allowed_access_types”: [],
“allowed_authorize_types”: [],
“auth_login_redirect”: “”
},
“auth”: {
“use_param”: false,
“param_name”: “”,
“use_cookie”: false,
“cookie_name”: “”,
“auth_header_name”: “Authorization”
},
“use_basic_auth”: false,
“enable_jwt”: true,
“use_standard_auth”: false,
“enable_coprocess_auth”: false,
“jwt_signing_method”: “hmac”,
“jwt_source”: “d3hJUEY2bGZ2SVFSaE9HMHoxQTBRd3hOUmZkak96Z2Y=”,
“jwt_identity_base_field”: “sub”,
“jwt_client_base_field”: “”,
“jwt_policy_field_name”: “policy-id”,
“notifications”: {
“shared_secret”: “”,
“oauth_on_keychange_url”: “”
},
“enable_signature_checking”: false,
“hmac_allowed_clock_skew”: -1,
“base_identity_provided_by”: “”,
“definition”: {
“location”: “header”,
“key”: “x-api-version”
},
“version_data”: {
“not_versioned”: true,
“versions”: {
“Default”: {
“name”: “Default”,
“expires”: “”,
“paths”: {
“ignored”: [],
“white_list”: [],
“black_list”: []
},
“use_extended_paths”: true,
“extended_paths”: {},
“global_headers”: {},
“global_headers_remove”: [],
“global_size_limit”: 0,
“override_target”: “”
}
}
},
“uptime_tests”: {
“check_list”: [],
“config”: {
“expire_utime_after”: 0,
“service_discovery”: {
“use_discovery_service”: false,
“query_endpoint”: “”,
“use_nested_query”: false,
“parent_data_path”: “”,
“data_path”: “”,
“port_data_path”: “”,
“target_path”: “”,
“use_target_list”: false,
“cache_timeout”: 60,
“endpoint_returns_list”: false
},
“recheck_wait”: 0
}
},
“proxy”: {
“preserve_host_header”: false,
“listen_path”: “/api/test”,
“target_url”: “http://localhost/api/test”,
“strip_listen_path”: true,
“enable_load_balancing”: false,
“target_list”: [],
“check_host_against_uptime_tests”: false,
“service_discovery”: {
“use_discovery_service”: false,
“query_endpoint”: “”,
“use_nested_query”: false,
“parent_data_path”: “”,
“data_path”: “hostname”,
“port_data_path”: “port”,
“target_path”: “/api-slug”,
“use_target_list”: false,
“cache_timeout”: 60,
“endpoint_returns_list”: false
}
},
“disable_rate_limit”: false,
“disable_quota”: false,
“custom_middleware”: {
“pre”: [],
“post”: [],
“post_key_auth”: [],
“auth_check”: {
“name”: “”,
“path”: “”,
“require_session”: false
},
“response”: [],
“driver”: “”,
“id_extractor”: {
“extract_from”: “”,
“extract_with”: “”,
“extractor_config”: {}
}
},
“custom_middleware_bundle”: “”,
“cache_options”: {
“cache_timeout”: 60,
“enable_cache”: true,
“cache_all_safe_requests”: false,
“cache_response_codes”: [],
“enable_upstream_cache_control”: false
},
“session_lifetime”: 0,
“active”: true,
“auth_provider”: {
“name”: “”,
“storage_engine”: “”,
“meta”: {}
},
“session_provider”: {
“name”: “”,
“storage_engine”: “”,
“meta”: null
},
“event_handlers”: {
“events”: {}
},
“enable_batch_request_support”: false,
“enable_ip_whitelisting”: false,
“allowed_ips”: [],
“dont_set_quota_on_create”: false,
“expire_analytics_after”: 0,
“response_processors”: [],
“CORS”: {
“enable”: false,
“allowed_origins”: [],
“allowed_methods”: [],
“allowed_headers”: [],
“exposed_headers”: [],
“allow_credentials”: false,
“max_age”: 24,
“options_passthrough”: false,
“debug”: false
},
“domain”: “”,
“do_not_track”: false,
“tags”: [],
“enable_context_vars”: false
}
my tyk version is v3.1.0 and my logs is
time=“Aug 16 05:37:18” level=info msg=“Attempted JWT access with non-existent key.” api_id=3 api_name=JWT-TEST mw=JWTMiddleware org_id=test-org origin=10.244.0.1 path=“/api/test”
time=“Aug 16 05:37:18” level=error msg=“JWT validation error” api_id=3 api_name=JWT-TEST error=“token contains an invalid number of segments” mw=JWTMiddleware org_id=test-org origin=10.244.0.1 path=“/api/test”

Hi @A.M.Saranya,

This error in the logs means the JWT is malformed. Please verify it on jwt.io.
Are you able to share the JWT?

I’ve tested using this, and the call works fine: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJwb2xpY3ktaWQiOiI2NGQ5ZmQ5ZjkwMGU0YjAwMDFkMTBmZTcifQ.RKEq7embdg6qT1N6T4_SkyEa8Pvg5Q4vidgC_3ARKMM

Hi ubong,
Inside api-definition file,jwt source: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJwb2xpY3ktaWQiOiI2NGQ5ZmQ5ZjkwMGU0YjAwMDFkMTBmZTcifQ.RKEq7embdg6qT1N6T4_SkyEa8Pvg5Q4vidgC_3ARKMM". or any other needs to be change.
For running curl command using post method this -H “Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJwb2xpY3ktaWQiOiI2NGQ5ZmQ5ZjkwMGU0YjAwMDFkMTBmZTcifQ.RKEq7embdg6qT1N6T4_SkyEa8Pvg5Q4vidgC_3ARKMM” it shows not found error.

Not Found error? That’s probably “policy not found”, is that right?

It’ll be because my policy id and yours are different. If you view my JWT on jwt.io, you’d see I have the policy id: 64d9fd9f900e4b0001d10fe7 in the payload. You should change that to your Policy ID, which I believe is “1” from the policy file you shared earlier.

Inside api-definition file,jwt source: eyJhbG…

Do you want to change that? I don’t think you want to. Even if you did, jwt_source should not be the JWT all over again.

In my earlier post, Here’s what I did.

  • I imported your API definition into my environment. I didn’t change anything.
  • I created a Policy that grants access to the API
  • I called the API like this: curl http://ocalhost:8080/api/test -H “Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJwb2xpY3ktaWQiOiI2NGQ5ZmQ5ZjkwMGU0YjAwMDFkMTBmZTcifQ.RKEq7embdg6qT1N6T4_SkyEa8Pvg5Q4vidgC_3ARKMM”
  • And the call was successful

Hi Ubong. Inside my api-definition file is same but I changed like this only,“jwt_source”: “”, and my policy file is.
{
“64d9fd9f900e4b0001d10fe7”: {
“rate”: 1000,
“id”: “64d9fd9f900e4b0001d10fe7”,
“per”: 1,
“quota_max”: 100,
“quota_renewal_rate”: 60,
“access_rights”: {
“3”: {
“api_name”: “JWT-TEST”,
“api_id”: “3”,
“versions”: [
“Default”
]
}
},
“org_id”: “test-org”,
“hmac_enabled”: false
}
}
and my logs is
time=“Aug 17 06:06:57” level=warning msg=“Key not found in storage engine” err=“key not found” inbound-key=“****7890” prefix=auth-mgr
time=“Aug 17 06:06:57” level=error msg=“Couldn’t get token” api_id=3 api_name=JWT-TEST error=“token invalid, key not found” mw=JWTMiddleware org_id=test-org origin=10.244.0.1 path=“/api/test”
time=“Aug 17 06:06:57” level=info msg=“Attempted JWT access with non-existent key.” api_id=3 api_name=JWT-TEST mw=JWTMiddleware org_id=test-org origin=10.244.0.1 path=“/api/test”
time=“Aug 17 06:06:57” level=error msg=“JWT validation error” api_id=3 api_name=JWT-TEST error=“token invalid, key not found” mw=JWTMiddleware org_id=test-org origin=10.244.0.1 path=“/api/test”
and am using curl command(if any other files need to be change).

Hi @A.M.Saranya,

It appears that there might be some confusion regarding your understanding of how JWTs integrate with Tyk. I kindly request you take a moment to review and follow the documentation in its entirety at your convenience. If you encounter any particular challenges or questions, please feel free to reach out.

PS: The screenshot of the Dashboard here,
corresponds with “jwt_source” in the raw API definition file, except that, in the raw definition file, this value is base64 encoded. So essentially, you should fill in dHlrMTIz, rather than tyk123 for the jwt_source when walking through the documentation to create a successful integration

Thank you for your attention to this matter.