{"record":{"id":"fadf6656cc747202","repo":"restsharp/RestSharp","slug":"token-request-failed-with-status-response-statusc","errorCode":null,"errorMessage":"Token request failed with status {response.StatusCode}: {body}","messagePattern":"Token request failed with status (.+?): (.+?)","errorType":"exception","errorClass":"HttpRequestException","httpStatus":null,"severity":"error","filePath":"src/RestSharp/Authenticators/OAuth2/OAuth2EndpointAuthenticatorBase.cs","lineNumber":91,"sourceCode":"\n        try {\n            if (_accessToken != null && DateTimeOffset.UtcNow < _tokenExpiry)\n                return _accessToken;\n\n            var parameters = BuildRequestParameters();\n\n            if (TokenRequest.ExtraParameters != null) {\n                foreach (var kvp in TokenRequest.ExtraParameters)\n                    parameters[kvp.Key] = kvp.Value;\n            }\n\n            using var content = new FormUrlEncodedContent(parameters);\n            using var response = await _tokenClient.PostAsync(TokenRequest.TokenEndpointUrl, content, cancellationToken).ConfigureAwait(false);\n\n            var body = await response.Content.ReadAsStringAsync().ConfigureAwait(false);\n\n            if (!response.IsSuccessStatusCode)\n                throw new HttpRequestException($\"Token request failed with status {response.StatusCode}: {body}\");\n\n            var tokenResponse = JsonSerializer.Deserialize<OAuth2TokenResponse>(body);\n\n            if (tokenResponse == null || string.IsNullOrEmpty(tokenResponse.AccessToken))\n                throw new InvalidOperationException($\"Token endpoint returned an invalid response: {body}\");\n\n            _accessToken = tokenResponse.AccessToken;\n            _tokenExpiry = tokenResponse.ExpiresIn.HasValue\n                ? DateTimeOffset.UtcNow.AddSeconds(tokenResponse.ExpiresIn.Value) - TokenRequest.ExpiryBuffer\n                : DateTimeOffset.MaxValue;\n\n            OnTokenResponse(tokenResponse);\n            TokenRequest.OnTokenRefreshed?.Invoke(tokenResponse);\n\n            return _accessToken;\n        }\n        finally {\n            _lock.Release();","sourceCodeStart":73,"sourceCodeEnd":109,"githubUrl":"https://github.com/restsharp/RestSharp/blob/6a5082169257438cd085f822f050d93256a8e499/src/RestSharp/Authenticators/OAuth2/OAuth2EndpointAuthenticatorBase.cs#L73-L109","documentation":"Thrown by the OAuth2 endpoint authenticator when the HTTP POST to the token endpoint returns a non-success status code. The message includes the status code and the raw response body for diagnostics. Raised inside GetOrRefreshTokenAsync after reading the body.","triggerScenarios":"The configured TokenRequest.TokenEndpointUrl returns 4xx/5xx, e.g. invalid client credentials (401), bad grant (400), expired/revoked refresh token, network-bridged 502, or wrong token endpoint URL.","commonSituations":"Wrong client_id/client_secret; token endpoint URL typo or pointing to the wrong environment; refresh token revoked server-side; client credentials not granted the required scope; clock skew causing grant rejection.","solutions":["Inspect the status code and body embedded in the exception message to identify the OAuth error (invalid_grant, invalid_client, etc.).","Verify TokenRequest.TokenEndpointUrl, client credentials, and scopes are correct for the target environment.","For invalid_grant due to expired refresh tokens, re-authenticate the user to obtain a fresh authorization code/refresh token.","Wrap token acquisition in retry logic for transient 5xx with exponential backoff."],"exampleFix":"// before\nvar authenticator = new OAuth2ClientCredentialsAuthenticator(request);\n\n// after\ntry {\n    await authenticator.Authenticate(client, req, ct);\n} catch (HttpRequestException ex) when (ex.Message.Contains(\"401\")) {\n    // credentials invalid - surface to operator\n    throw new InvalidOperationException(\"OAuth client credentials rejected by token endpoint\", ex);\n}","handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"try { await authenticator.Authenticate(client, request, ct); } catch (HttpRequestException ex) when (ex.Message.Contains(\"Token request failed\")) { /* inspect status/body, re-auth on invalid_grant, retry on 5xx */ }","preventionTips":["Verify client credentials and token endpoint URL before deployment.","Log the status code and body from the exception for fast root-cause analysis.","Implement retry with backoff for transient 5xx responses."],"tags":["oauth","oauth2","authentication","network","token"],"backgroundTag":null,"analyzedSha":"6a5082169257438cd085f822f050d93256a8e499","analyzedAt":"2026-08-13T20:38:25.807Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}