wuyouzhuguli/SpringAll · error · BadCredentialsException

Failed to decode basic authentication token

Error message

Failed to decode basic authentication token

What it means

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 ').

Source

Thrown at 64.Spring-Security-OAuth2-Customize/src/main/java/cc/mrbird/security/handler/MyAuthenticationSucessHandler.java:82

        OAuth2Authentication auth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);

        // 7. 通过 AuthorizationServerTokenServices 生成 OAuth2AccessToken
        OAuth2AccessToken token = authorizationServerTokenServices.createAccessToken(auth2Authentication);

        // 8. 返回 Token
        log.info("登录成功");
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(new ObjectMapper().writeValueAsString(token));
    }

    private String[] extractAndDecodeHeader(String header, HttpServletRequest request) {
        byte[] base64Token = header.substring(6).getBytes(StandardCharsets.UTF_8);

        byte[] decoded;
        try {
            decoded = Base64.getDecoder().decode(base64Token);
        } catch (IllegalArgumentException var7) {
            throw new BadCredentialsException("Failed to decode basic authentication token");
        }

        String token = new String(decoded, StandardCharsets.UTF_8);
        int delim = token.indexOf(":");
        if (delim == -1) {
            throw new BadCredentialsException("Invalid basic authentication token");
        } else {
            return new String[]{token.substring(0, delim), token.substring(delim + 1)};
        }
    }
}

View on GitHub (pinned to 614d2578d9)

Solutions

  1. Generate the header with standard Base64 of the UTF-8 bytes of 'clientId:clientSecret' (e.g. JS btoa, Java Base64.getEncoder().encodeToString).
  2. Ensure no whitespace/newlines inside the base64 segment after 'Basic '.
  3. Use the standard (+ and /) alphabet, not URL-safe (- and _).

Example fix

// before (manual, invalid)
// headers: { 'Authorization': 'Basic abc 123!!!' }

// after
const basic = btoa('clientId:clientSecret'); // standard base64
headers: { 'Authorization': 'Basic ' + basic }
Defensive patterns

Strategy: validation

Validate before calling

// Build the header only with a vetted base64 helper; validate the result.
function basicHeader(id, secret) {
  const raw = `${id}:${secret}`;
  const b64 = btoa(raw); // standard base64
  if (!/^[A-Za-z0-9+/]*={0,2}$/.test(b64)) throw new Error('bad base64');
  return 'Basic ' + b64;
}

Try / catch

try { await login(); }
catch (e) {
  if (/Failed to decode/.test(e.message)) { /* rebuild header with btoa */ }
  else handleError(e);
}

Prevention

When it happens

Trigger: 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.

Common situations: Frontend built the header manually instead of using btoa/atob; copy-paste introduced spaces or newlines; Java/JS base64url variant used unintentionally.

Understand the failure class

Related errors


AI-assisted analysis of wuyouzhuguli/SpringAll@614d2578d9 (2026-08-14). Data as JSON: /api/errors/faaa52c50ec94e21. Report an issue: GitHub.