{"record":{"id":"faaa52c50ec94e21","repo":"wuyouzhuguli/SpringAll","slug":"failed-to-decode-basic-authentication-token","errorCode":null,"errorMessage":"Failed to decode basic authentication token","messagePattern":"Failed to decode basic authentication token","errorType":"exception","errorClass":"BadCredentialsException","httpStatus":null,"severity":"error","filePath":"64.Spring-Security-OAuth2-Customize/src/main/java/cc/mrbird/security/handler/MyAuthenticationSucessHandler.java","lineNumber":82,"sourceCode":"        OAuth2Authentication auth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);\n\n        // 7. 通过 AuthorizationServerTokenServices 生成 OAuth2AccessToken\n        OAuth2AccessToken token = authorizationServerTokenServices.createAccessToken(auth2Authentication);\n\n        // 8. 返回 Token\n        log.info(\"登录成功\");\n        response.setContentType(\"application/json;charset=UTF-8\");\n        response.getWriter().write(new ObjectMapper().writeValueAsString(token));\n    }\n\n    private String[] extractAndDecodeHeader(String header, HttpServletRequest request) {\n        byte[] base64Token = header.substring(6).getBytes(StandardCharsets.UTF_8);\n\n        byte[] decoded;\n        try {\n            decoded = Base64.getDecoder().decode(base64Token);\n        } catch (IllegalArgumentException var7) {\n            throw new BadCredentialsException(\"Failed to decode basic authentication token\");\n        }\n\n        String token = new String(decoded, StandardCharsets.UTF_8);\n        int delim = token.indexOf(\":\");\n        if (delim == -1) {\n            throw new BadCredentialsException(\"Invalid basic authentication token\");\n        } else {\n            return new String[]{token.substring(0, delim), token.substring(delim + 1)};\n        }\n    }\n}\n","sourceCodeStart":64,"sourceCodeEnd":94,"githubUrl":"https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/64.Spring-Security-OAuth2-Customize/src/main/java/cc/mrbird/security/handler/MyAuthenticationSucessHandler.java#L64-L94","documentation":"BadCredentialsException thrown in extractAndDecodeHeader when Base64.getDecoder().decode(base64Token) raises IllegalArgumentException — i.e. the payload after 'Basic ' is not valid Base64 (RFC 4648). The input is header.substring(6) (everything after 'Basic ').","triggerScenarios":"The Basic header contains characters outside the Base64 alphabet; the value is truncated or has stray whitespace; URL-safe base64 (-/_) used where standard (+/) is required; the client hand-built the header incorrectly.","commonSituations":"Frontend built the header manually instead of using btoa/atob; copy-paste introduced spaces or newlines; Java/JS base64url variant used unintentionally.","solutions":["Generate the header with standard Base64 of the UTF-8 bytes of 'clientId:clientSecret' (e.g. JS btoa, Java Base64.getEncoder().encodeToString).","Ensure no whitespace/newlines inside the base64 segment after 'Basic '.","Use the standard (+ and /) alphabet, not URL-safe (- and _)."],"exampleFix":"// before (manual, invalid)\n// headers: { 'Authorization': 'Basic abc 123!!!' }\n\n// after\nconst basic = btoa('clientId:clientSecret'); // standard base64\nheaders: { 'Authorization': 'Basic ' + basic }","handlingStrategy":"validation","validationCode":"// Build the header only with a vetted base64 helper; validate the result.\nfunction basicHeader(id, secret) {\n  const raw = `${id}:${secret}`;\n  const b64 = btoa(raw); // standard base64\n  if (!/^[A-Za-z0-9+/]*={0,2}$/.test(b64)) throw new Error('bad base64');\n  return 'Basic ' + b64;\n}","typeGuard":null,"tryCatchPattern":"try { await login(); }\ncatch (e) {\n  if (/Failed to decode/.test(e.message)) { /* rebuild header with btoa */ }\n  else handleError(e);\n}","preventionTips":["Never hand-build the Basic header; always use btoa/Base64.getEncoder.","Avoid URL-safe base64 for HTTP Basic.","Strip whitespace from the base64 segment."],"tags":["oauth2","encoding","authentication","spring-security","base64"],"backgroundTag":null,"analyzedSha":"614d2578d9495acf53cc02f2dee9c6131cc5e51a","analyzedAt":"2026-08-14T04:40:03.488Z","schemaVersion":2},"datasetVersion":"2026-08-14T05:17:29.042Z"}