{"record":{"id":"591c97c4e52689f6","repo":"alibaba/nacos","slug":"authentication-failed-errormessage","errorCode":null,"errorMessage":"Authentication failed: {errorMessage}","messagePattern":"Authentication failed: (.+?)","errorType":"exception","errorClass":"AccessException","httpStatus":401,"severity":"error","filePath":"plugin-default-impl/nacos-oidc-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/oidc/authenticate/AuthorizationCodeHandler.java","lineNumber":203,"sourceCode":"            } else if (!stateData.nonce.equals(tokenNonce)) {\n                String message = String.format(\"Nonce mismatch: expected %s, got %s\",\n                    stateData.nonce, tokenNonce);\n                LOGGER.error(\"{} - Possible token replay attack detected\", message);\n                throw new AccessException(message);\n            }\n            \n            // Map claims to user\n            OidcUser user = userMapper.mapToUser(claims);\n            user.setToken(tokens.getAccessToken().getValue());\n            \n            LOGGER.info(\"User authenticated via authorization code: {}\", user.getUsername());\n            return user;\n            \n        } catch (AccessException e) {\n            throw e;\n        } catch (Exception e) {\n            LOGGER.error(\"Failed to exchange code for tokens\", e);\n            throw new AccessException(\"Authentication failed: \" + e.getMessage());\n        }\n    }\n    \n    /**\n     * Exchange authorization code for OIDC tokens.\n     *\n     * @param code        authorization code\n     * @param redirectUri redirect URI\n     * @return OIDC tokens\n     * @throws Exception if exchange fails\n     */\n    private OIDCTokens exchangeCodeForTokens(String code, String redirectUri) throws Exception {\n        String tokenEndpoint = metadataProvider.getMetadata().getTokenEndpoint();\n        if (StringUtils.isBlank(tokenEndpoint)) {\n            throw new AccessException(\"Token endpoint not configured\");\n        }\n        \n        // Build token request","sourceCodeStart":185,"sourceCodeEnd":221,"githubUrl":"https://github.com/alibaba/nacos/blob/9b989acdf181d00898f2e8839257bb2b2a3cefe3/plugin-default-impl/nacos-oidc-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/oidc/authenticate/AuthorizationCodeHandler.java#L185-L221","documentation":"Thrown by AuthorizationCodeHandler.exchangeCodeForUser as the catch-all for any non-AccessException during the code-for-user exchange flow (state decode, token exchange, ID-token validation, claim mapping). The handler wraps the original message into AccessException(\"Authentication failed: \" + e.getMessage()) and logs the full stack trace at ERROR. AccessException instances are rethrown unchanged before this catch.","triggerScenarios":"Any unexpected Exception in exchangeCodeForUser outside the explicit AccessException paths: token endpoint HTTP call fails, ID-token signature validation throws, userMapper.mapToUser throws, or tokens.getAccessToken() returns null causing an NPE.","commonSituations":"The IdP token endpoint is unreachable or returns an error not caught by the explicit handling; the JWT validator rejects the ID token signature (JWK mismatch); the access token is null; a claim-mapping misconfiguration throws during user creation.","solutions":["Read the server log for 'Failed to exchange code for tokens' — it logs the original exception with the true root cause.","If it's a token-endpoint network error, verify the IdP token endpoint URL and network reachability.","If it's a signature validation error, confirm the JWKS/issuer config matches the IdP.","Fix the specific underlying exception identified in the stack trace."],"exampleFix":null,"handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"try {\n    OidcUser user = handler.exchangeCodeForUser(code, state, redirectUri);\n} catch (AccessException e) {\n    // AccessException is the base; check server log 'Failed to exchange code for tokens'\n    // for the original exception to find the true root cause\n}","preventionTips":["Always check the server-side ERROR log for the wrapped exception's real cause.","Verify IdP token endpoint reachability and JWKS/issuer config.","Test the full OIDC flow end-to-end before production rollout.","Do not retry unchanged; fix the underlying failure first."],"tags":["auth","oidc","generic-catch","token-exchange","access-denied","java"],"backgroundTag":null,"analyzedSha":"9b989acdf181d00898f2e8839257bb2b2a3cefe3","analyzedAt":"2026-08-14T07:17:31.569Z","schemaVersion":2},"datasetVersion":"2026-08-14T10:17:34.591Z"}