{"record":{"id":"b4b2495ad2ab6eb3","repo":"karatelabs/karate","slug":"token-refresh-failed-server-returned-invalid-json-response","errorCode":null,"errorMessage":"Token refresh failed: server returned invalid JSON response","messagePattern":"Token refresh failed: server returned invalid JSON response","errorType":"exception","errorClass":"OAuth2Exception","httpStatus":null,"severity":"error","filePath":"karate-core/src/main/java/io/karatelabs/http/OAuth2TokenManager.java","lineNumber":87,"sourceCode":"            HttpResponse response = builder.invoke(\"post\");\n            String body = response.getBodyString();\n            int status = response.getStatus();\n\n            if (status < 200 || status >= 300) {\n                String errorMessage = parseOAuthError(body, status);\n                logger.error(\"Token refresh failed: {}\", errorMessage);\n                currentToken = null;\n                throw new OAuth2Exception(errorMessage);\n            }\n\n            Json json;\n            try {\n                json = Json.of(body);\n            } catch (Exception e) {\n                String errorMessage = \"Token refresh failed: server returned invalid JSON response\";\n                logger.error(errorMessage);\n                currentToken = null;\n                throw new OAuth2Exception(errorMessage);\n            }\n\n            if (!json.isObject()) {\n                String errorMessage = \"Token refresh failed: expected JSON object but received \" +\n                    (json.isArray() ? \"array\" : \"primitive value\");\n                logger.error(errorMessage);\n                currentToken = null;\n                throw new OAuth2Exception(errorMessage);\n            }\n\n            Map<String, Object> data = json.asMap();\n            OAuth2Token newToken = OAuth2Token.fromMap(data);\n            storeToken(newToken);\n            logger.debug(\"Token refreshed successfully\");\n            return newToken;\n        } catch (OAuth2Exception e) {\n            throw e;\n        } catch (Exception e) {","sourceCodeStart":69,"sourceCodeEnd":105,"githubUrl":"https://github.com/karatelabs/karate/blob/a22eb90246d958d15a47bf436693d0121ad2812d/karate-core/src/main/java/io/karatelabs/http/OAuth2TokenManager.java#L69-L105","documentation":"OAuth2TokenManager.refreshToken() expects the token endpoint to return a JSON body. If Json.of(body) cannot parse the HTTP response, the manager clears the cached token and throws OAuth2Exception with this message, because a non-JSON response cannot contain a valid token payload.","triggerScenarios":"Token endpoint returns HTML (login/error page), empty body, proxy interstitial, or plain text instead of JSON during refresh.","commonSituations":"Wrong token URL configured; expired redirect to a login page; corporate proxy or WAF injecting HTML; server 5xx returning text/plain error page.","solutions":["Verify the OAuth2 token endpoint URL returns JSON (curl it and inspect the body).","Check HTTP status and response body on the failing request — log the raw body before parsing.","Fix proxy/WAF interference or point to the correct issuer token endpoint.","Handle OAuth2Exception by re-authenticating from scratch (credentials grant) rather than refresh.","­"],"exampleFix":"// before\nvar mgr = new OAuth2TokenManager(cfg.tokenUrlWrong);\n// after\nvar mgr = new OAuth2TokenManager(\"https://idp.example.com/oauth2/token\"); // returns application/json","handlingStrategy":"try-catch","validationCode":"// verify endpoint before configuring: curl -s $TOKEN_URL must return JSON\ncurl -s -o /dev/null -w '%{content_type}' $TOKEN_URL # expect application/json","typeGuard":null,"tryCatchPattern":"try { token = mgr.refresh(); } catch (OAuth2Exception e) { if (e.getMessage().contains('invalid JSON')) { log.error('Token endpoint returned non-JSON: check URL/proxy'); reauthenticate(); } else throw e; }","preventionTips":["Point tokenUrl at the RFC 6749 token endpoint returning application/json","Check for proxy/WAF HTML interstitials in your environment","Validate the endpoint with curl before wiring it into config","Log the raw response body on failure to diagnose quickly"],"tags":["oauth2","token-refresh","invalid-json"],"backgroundTag":"invalid-json-response","analyzedSha":"a22eb90246d958d15a47bf436693d0121ad2812d","analyzedAt":"2026-09-12T09:01:00.220Z","contentChangedAt":"2026-09-12T09:01:00.220Z","schemaVersion":2},"datasetVersion":"2026-09-16T19:17:19.609Z"}