Skip to main content

When OAuth Fails in the Real World: Debugging Google OAuth, PKCE, and Client Secrets

An engineering case study in callback validation, token exchange, credential security, and the limits of successful tests.

Updated 20 min readMarkdown
Part of seriesLORQAI Engineering Diaries
When OAuth Fails in the Real World: Debugging Google OAuth, PKCE, and Client Secrets

LORQAI Engineering Diaries — 001

Our recorded local tests passed. Our credential storage worked under the tested conditions. The OAuth client was configured, and the application was ready to request read-only access to Google Search Console.

Then we connected a real Google account.

The browser returned to localhost with a remarkably unhelpful message:

Authorization was not completed. Return to Studio and try again.

What followed was not one OAuth failure with one straightforward solution. It was a sequence of problems at different stages of the authorization process.

First, our callback handler rejected an authorization response parameter. Later, the token endpoint rejected an exchange request. Along the way, we discovered weaknesses in our session binding, diagnostic reporting, and definition of a successful connection.

The integration eventually reached a reported successful authorization and Search Console property discovery. But reconstructing the development history revealed something important: the evidence supported the sequence of events more strongly than it supported any single explanation for the final success.

This is what happened, what we changed, and what we learned from investigating a real OAuth integration.

1. The problem we were actually trying to solve

We were building LORQAI Studio 3, a local-first creative publishing and operations application for macOS.

The application combines a Go backend, a React and TypeScript interface, SQLite for local application data, and operating-system facilities for credential storage.

Google Search Console was intended to become an additional source of operational information, allowing us to examine search performance and indexing without introducing a separate cloud backend.

Our permission model was deliberately narrow.

The connector implementation requested:

https://www.googleapis.com/auth/webmasters.readonly

We did not need access to email, documents, calendars, or permission to modify Search Console properties.

The development records describe a Desktop OAuth client using an external browser, a loopback callback, Authorization Code Flow with PKCE S256, and macOS Keychain.

The intended design separated authorization, credential storage, property selection, and data collection. Each would have its own observable outcome.

That separation became considerably more important once the live failures began.

A note about the evidence

This case study was reconstructed from historical source revisions, existing development records, and recorded test results.

The source history establishes changes to the implementation. The development records describe historical runtime outcomes. Mock and synthetic tests establish behavior under their respective test conditions.

The original token request and full provider error response were not retained. No additional live experiments were performed during the evidence-recovery investigation.

The protocol examples below are illustrative, not captured production traffic.

2. Why Personal mode is worth knowing about

While researching authorization options for a single-owner application, we examined Google's Personal mode.

Google documents this mode as an alternative for applications intended exclusively for the account that creates them. It avoids the seven-day test-user token expiration associated with External Testing and does not require the usual app verification process.

There are trade-offs. Personal mode is restricted to the creating account, and it cannot subsequently be converted into an External or Internal application.

It also does not eliminate every possible reason for token expiration or revocation.

For local-first applications, this is an attractive configuration to consider. But the historical technical records recovered for this article do not independently establish the audience settings of the specific OAuth client used in every authorization attempt.

We therefore do not attribute the failures or subsequent success to Personal mode.

That distinction matters: a documented platform feature is not evidence of how a particular client was configured or how a particular request behaved.

3. Failure one: the callback rejected the issuer parameter

The development ledger records that an early authorization attempt reached the application's callback handler but failed before token exchange.

The problem involved an additional authorization-response parameter:

iss

At the time, our callback implementation rejected the parameter.

This was not merely an arbitrary provider-specific extension. The issuer identifier is a defined OAuth security mechanism.

RFC 9207 specifies its use in authorization responses to help clients defend against authorization-server mix-up attacks.

Google's published discovery metadata identifies its issuer as:

https://accounts.google.com

The metadata also advertises support for the authorization-response issuer parameter:

{
  "issuer": "https://accounts.google.com",
  "authorization_response_iss_parameter_supported": true
}

This excerpt describes public provider metadata, not a captured response from our application.

The historical source correction changed the callback handler to accept the expected Google issuer while retaining the existing state and other callback checks.

The distinction is important: supporting iss does not mean accepting every issuer value.

RFC 9207, Section 2.4 defines specific validation requirements for clients implementing this mechanism.

When an authorization response contains iss, the client must extract and form-decode its value, then compare it with the expected issuer of the authorization server to which the original request was sent. The comparison must be an exact string comparison, rather than a comparison based on URL normalization.

When authorization-server metadata is used, the expected value comes from the server's published issuer field. Otherwise, it must come from an appropriate trusted deployment-specific configuration.

If the values differ, the client must reject the authorization response and must not continue the grant. For an error response, it must not assume that the error came from the intended authorization server.

Missing issuer values also require attention. When a client supports both servers that implement issuer identification and servers that do not, it must retain each server's support status and reject responses without iss from servers configured as supporting it.

A client can also adopt a stricter policy that exclusively supports authorization servers returning iss and rejects responses that omit it.

The recovered evidence establishes our change to expected-issuer handling and recorded test coverage. It is not a comprehensive security audit or proof that every issuer-validation requirement, including missing-issuer handling, was satisfied by every installed release.

The initial callback failure was therefore a problem distinct from the token exchange issue that emerged later.

4. Strengthening the authorization session

The investigation exposed a second architectural concern: an authorization attempt needed to remain associated with the exact application context that initiated it.

The historical source changes introduced stricter binding to the selected website, configuration revision, OAuth client, and application installation.

They also restricted the connector to one active authorization operation and introduced an account-selection hint.

An account hint can improve the sign-in experience, but it must not be mistaken for proof that a particular Google account has been authorized.

Another change concerned the meaning of success.

Previously, a callback result could be too loosely connected to the later credential-storage outcome. The revised flow delayed its successful completion result until the credential save and readback operations had completed.

Conceptually, the integration now distinguished these stages:

Start authorization session
            |
            v
Open external browser
            |
            v
Receive loopback callback
            |
            v
Validate authorization response
            |
            v
Exchange authorization code
            |
            v
Save and read back credentials
            |
            v
Verify access to provider resources

This is a conceptual representation of the workflow, not a complete implementation diagram.

Securing the loopback callback

For desktop applications using loopback redirects, RFC 8252, Sections 7.3 and 8.3 provide important security guidance.

The temporary callback listener should bind exclusively to a loopback interface, such as 127.0.0.1 or ::1, rather than an externally accessible network interface.

Where supported, the application can obtain an available port dynamically from the operating system and use that port in its authorization request.

The callback listener should exist only for the authorization operation and close after the expected response is received or the operation terminates.

As additional session-management safeguards, the application should generate unpredictable transaction-specific state, validate it against the initiating session, enforce a bounded session lifetime, and invalidate completed or expired sessions so they cannot be reused.

The local HTTP callback is a specific exception permitted for loopback communication that remains on the device. It does not justify unencrypted communication with remote OAuth endpoints. Authorization and token-exchange requests to Google must use HTTPS.

Loopback binding also does not eliminate the possibility of interference from another local process. PKCE remains essential.

These are protocol and implementation recommendations, not claims that every safeguard was independently verified in the historical Studio release.

The source history establishes that several changes were introduced before the later successful authorization. That fact becomes important when assessing which change ultimately resolved the problem.

5. Failure two: the token endpoint rejected the request

After the callback-related correction, a later installed flow reportedly reached token exchange but could not complete it.

The initial diagnostic record lacked the upstream HTTP status and OAuth error information needed to investigate the rejection.

The problem was no longer merely an unsuccessful authorization. It was an unsuccessful authorization with insufficient evidence to identify the failure precisely.

We therefore improved the diagnostic implementation.

Instead of retaining raw OAuth responses, the connector recorded selected HTTP status information, allowlisted OAuth error codes, and a narrowly defined local classification for relevant missing-parameter errors.

A subsequent development-ledger entry reported:

Field Recorded result
Failure stage token_exchange
HTTP status 400
OAuth error invalid_request
Studio diagnostic classification client_secret_missing

The table is a reconstruction of the retained sanitized information, not an original HTTP response.

The last field is particularly important.

client_secret_missing is a classification produced by Studio. It is not a standardized OAuth error code, and it must not be quoted as Google's original error description.

Historical source inspection established that the classifier recognized wording associated with a missing or required parameter.

The original provider wording was intentionally not retained. We cannot reconstruct it with certainty.

However, the source history established another relevant fact: the code-exchange implementation did not include the client_secret field.

That is evidence about the implementation. It is not a captured inventory of the exact parameters transmitted during the failed live request.

Together, the diagnostic record and source history provided a reasonable direction for investigation.

They did not yet prove causality.

6. The client-secret interoperability question

Google's OAuth 2.0 documentation for desktop applications describes client_secret as optional for the authorization-code exchange. It also describes the parameter as optional in its refresh-token request documentation.

Our initial implementation omitted it.

The subsequent diagnostic suggested that the token endpoint's rejection might relate to the absence of that parameter.

The historical correction introduced optional Client Secret configuration, protected storage, and conditional inclusion of the configured value in both authorization-code and refresh-token grants.

It did not make the secret mandatory for every configuration.

PKCE S256 was preserved.

A later development-ledger entry reported successful authorization using the configured client and secret.

It is tempting to turn this into a simple conclusion: the documentation said optional, the server required it, and adding the secret fixed everything.

But that conclusion would go beyond our evidence.

The original provider error description is unavailable. The precise failed request was not captured. Other authorization-flow and configuration changes had also occurred, and the provider-side client settings were not independently recovered.

We therefore cannot establish that the secret was the only relevant difference between the failed and successful attempts.

What we can establish is the sequence: the source omitted the field, a missing-secret classification was recorded, optional secret support was added, and successful authorization was subsequently reported.

That is an interoperability observation worth investigating, not a universal rule about Google Desktop OAuth.

7. Five OAuth mechanisms that serve different purposes

One of the risks during OAuth troubleshooting is treating every security parameter as interchangeable.

They are not.

Mechanism Responsibility
PKCE Prevents unauthorized redemption of an intercepted authorization code by requiring possession of the original verifier.
State Correlates the authorization response with the initiating transaction and helps prevent CSRF when correctly generated and validated.
Issuer validation Checks that the authorization response belongs to the expected authorization server.
Redirect URI Defines the callback destination and participates in binding the code exchange to the original authorization request.
Client credentials Identify the registered client and satisfy applicable provider-specific client credential requirements.

These mechanisms complement one another.

PKCE does not prevent an authorization code from being intercepted. It is designed to prevent an interceptor who lacks the corresponding verifier from successfully redeeming that code.

Adding a provider-issued client secret is not a substitute for this protection.

RFC 8252, Section 8.5 explains why a shared secret included in distributed native applications cannot be relied upon as evidence of a confidential client identity.

A secret configured separately and protected locally is preferable to embedding it in source code. Nevertheless, its presence does not automatically transform a native application into a confidential OAuth client.

The security architecture must still reflect the application's actual ability to protect credentials.

Illustrative authorization request

The following example shows the relevant fields for a browser-based desktop authorization request.

GET https://accounts.google.com/o/oauth2/v2/auth

response_type = code
client_id = EXAMPLE_CLIENT_ID
redirect_uri = http://127.0.0.1:49152/oauth-example
scope = https://www.googleapis.com/auth/webmasters.readonly
state = RANDOM_TRANSACTION_STATE
code_challenge = DERIVED_PKCE_CHALLENGE
code_challenge_method = S256
access_type = offline

The parameters are displayed separately for readability. An actual request encodes them into the authorization URL.

The loopback port, callback path, identifiers, and transaction values are fictional. They do not represent the historical application configuration.

The access_type=offline field is a Google-specific authorization parameter associated with requesting offline access. It is not a universal OAuth requirement, nor is its presence alone a guarantee that a refresh token will be issued in a particular transaction.

The application must handle the actual token response and any applicable provider conditions rather than infer refresh-token availability from the authorization request.

PKCE S256 derives the challenge using:

BASE64URL-ENCODE(
    SHA256(ASCII(code_verifier))
)

The Base64url representation omits padding.

The verifier must be generated with sufficient cryptographic randomness and satisfy the requirements of RFC 7636. The derived challenge is sent during authorization; the original verifier is supplied during the code exchange.

The verifier remains associated with its individual authorization transaction.

Illustrative authorization-code exchange

The corresponding token request uses an HTTPS POST:

POST /token HTTP/1.1
Host: oauth2.googleapis.com
Content-Type: application/x-www-form-urlencoded

Its conceptual form fields are:

grant_type = authorization_code
client_id = EXAMPLE_CLIENT_ID
code = ONE_TIME_AUTHORIZATION_CODE
redirect_uri = http://127.0.0.1:49152/oauth-example
code_verifier = ORIGINAL_PKCE_VERIFIER
client_secret = EXAMPLE_CLIENT_SECRET

The actual request body must be form-encoded according to RFC 6749, Appendix B.

For example, the illustrative fields above would serialize into a single request body as follows:

grant_type=authorization_code&client_id=EXAMPLE_CLIENT_ID&code=ONE_TIME_AUTHORIZATION_CODE&redirect_uri=http%3A%2F%2F127.0.0.1%3A49152%2Foauth-example&code_verifier=ORIGINAL_PKCE_VERIFIER&client_secret=EXAMPLE_CLIENT_SECRET

This example demonstrates the wire-format encoding of the fields, including the percent-encoded redirect URI and ampersand-separated parameter pairs. The values are placeholders, not valid session credentials or a runnable token request.

The client_secret field illustrates the configured-secret variant. When no secret is configured and the provider supports omission, that field is omitted rather than populated with an invented value.

The redirect URI must match the one used in the corresponding authorization request.

Illustrative refresh-token exchange

The corrected implementation also supported the configured secret in refresh requests:

POST https://oauth2.googleapis.com/token

grant_type = refresh_token
client_id = EXAMPLE_CLIENT_ID
refresh_token = STORED_REFRESH_TOKEN
client_secret = EXAMPLE_CLIENT_SECRET

The request uses form encoding and the same conditional credential principle.

A refresh request is not another authorization-code exchange. It does not ordinarily repeat the original PKCE verifier, state, or callback parameters.

Although mock coverage and historical source changes establish support for the refresh grant, successful live token renewal was not established by the recovered evidence.

These examples are protocol illustrations, not executable demonstrations or recovered network traffic.

8. What the Keychain tests actually established

Credential security was another part of the integration that required careful interpretation.

The development records describe synthetic Keychain tests covering:

  • Saving a test credential.
  • Reading the credential back.
  • Removing it.
  • Confirming its absence after removal.
  • Retrieving a synthetic credential following a controlled restart.

These tests provided useful evidence that the application's credential-storage mechanism behaved as intended within those tested conditions.

They did not prove that a real Google refresh token would survive every subsequent application restart or update.

The corrected connector used macOS Keychain for the configured client secret and refresh credential.

This approach follows the direction of Google's OAuth security recommendations and Apple's platform-provided credential-storage mechanisms.

The intended separation was:

Information Storage responsibility
Non-secret OAuth configuration Application configuration
Configured client secret macOS Keychain
Refresh credential macOS Keychain
State and PKCE verifier Temporary authorization session
Operational diagnostics Sanitized application records

The later successful-flow report states that the real refresh credential was saved and read back through the completion path. It also records a subsequent successful property-list request.

This is stronger than a synthetic storage test, but it is still point-in-time, historically reported evidence.

The recovered records do not establish real Google credential retrieval following a restart, persistence through a managed application update, or successful access-token renewal.

Secure storage is an architectural decision. Durable real-world operation requires additional evidence.

9. Diagnostics should reveal the failure, not the credential

The original callback message was convenient for avoiding accidental information disclosure.

It was considerably less convenient for understanding why the integration had failed.

A better diagnostic system needs to distinguish at least the following categories:

  • Authorization denied.
  • Invalid or unexpected issuer.
  • Invalid or expired state.
  • Callback failure.
  • Token exchange rejection.
  • Credential persistence failure.
  • Provider resource-access failure.

These categories should not require exposing full provider responses or sensitive request parameters.

Our historical implementation changes introduced allowlisted OAuth diagnostics and tests intended to prevent disclosure of provider response bodies and credentials.

For example, a diagnostic system could retain a record shaped like this:

{
  "stage": "token_exchange",
  "http_status": 400,
  "oauth_error": "invalid_request",
  "local_classification": "client_secret_missing"
}

This is an illustrative diagnostic schema based on the retained categories, not a verbatim application log.

It deliberately excludes authorization codes, token values, client secrets, state values, PKCE verifiers, and complete callback URLs.

The trade-off is that overly aggressive redaction can leave insufficient evidence for later investigation.

That is what happened with the original provider description in our case.

A useful diagnostic design must decide in advance which non-sensitive facts will be necessary to understand a failure: the protocol stage, response status, recognized error category, presence or absence of expected request fields, and relevant configuration provenance.

Those facts can often be retained without recording credential values.

The goal is evidence-rich diagnostics, not indiscriminate logging.

10. A valid token is not the same as a verified resource

The development ledger subsequently recorded a successful authorization and Search Console property discovery.

Google's Sites: list endpoint returns the properties accessible to the authorized account and their permission levels.

A domain property can be represented by an identifier such as:

sc-domain:example.com

For our application, successful property discovery was particularly important because development previews and production websites have different identities.

A valid token must not cause observations belonging to a production domain to be attributed to a test deployment.

The recorded successful flow included selection and binding of the intended production property, followed by another successful property-list read.

This established a reported provider-access milestone.

It did not establish successful retrieval of every kind of Search Console information.

The API offers separate operations for search analytics, sitemap information, and indexed-URL inspection. Each has its own request requirements and possible failure modes.

The evidence recovered for this article did not establish that those collection operations had completed, that their results had been archived, or that observations could be attributed to a specific website build or deployment artifact.

Those remain distinct acceptance milestones.

A connection is not fully operational merely because an authorization browser displays a success page.

11. What the tests proved — and what they did not

The development records also identify focused tests for authorization-code and refresh-token exchanges, optional-secret handling, issuer and state validation, session binding, error classification, and protection against accidental credential disclosure.

These were reported mock-provider, local-loopback, and synthetic tests. They were not independently rerun during the evidence-recovery investigation.

The different forms of evidence answer different questions:

Evidence What it can establish
Historical source revisions Which implementation changes were introduced and in what order.
Mock-provider tests Behavior against controlled responses and expected request fields.
Synthetic Keychain tests Local credential-storage behavior under tested conditions.
Historical runtime reports Recorded outcomes of particular real authorization attempts.
Successful property discovery Reported access to the intended provider resource at a particular point in time.

None of these automatically establishes that adding a client secret alone caused the successful authorization.

For that, we would need stronger evidence isolating the change, such as otherwise-equivalent attempts differing only in whether the configured secret was supplied.

Our historical investigation did not contain such an experiment.

Nor did it independently recover the original request and response in sufficient detail to eliminate the alternative explanations.

The most defensible conclusion is therefore:

The sequence is established; causality is not isolated.

12. What we would change in the next integration

If we were implementing another desktop OAuth connector, we would start with more precise acceptance boundaries.

First, we would examine provider metadata and supported authorization-response extensions before finalizing callback handling.

Second, we would make every authorization transaction independently identifiable without recording its sensitive values. The initiating configuration and expected resource should remain associated with the entire operation.

Third, we would design diagnostic categories before connecting a real account. A rejected callback and a rejected token request should never be indistinguishable.

Fourth, we would support applicable provider credential requirements without weakening the public-client security model, PKCE, issuer validation, state validation, or redirect handling.

Finally, we would distinguish credential persistence, property discovery, data collection, token renewal, and long-term operational reliability in our acceptance criteria.

These are not merely testing details. They influence the architecture of the connector and the quality of the evidence available when something fails.

Conclusion

What began as a straightforward Google Search Console integration became a lesson in identifying the boundaries of a real software system.

The first failure involved callback handling. A later failure occurred during token exchange. Session binding and completion semantics also changed. Diagnostic improvements made the second failure more informative, and configurable client-secret support preceded a reported successful authorization.

We learned more by investigating those stages individually than we would have learned by attributing the entire experience to a single missing parameter.

Automated tests, security standards, official documentation, and AI-assisted development all contributed to the process.

But each contributed a different kind of evidence.

The important question was not whether we could display a successful result. It was whether we could explain what that result actually established.

A green checkmark is useful only when you know exactly what it represents.


References

Google documentation

OAuth standards and security guidance

Apple documentation


Editorial transparency: This article documents a real LORQAI development experience. ChatGPT assisted with research, technical analysis, drafting, and editorial revision. Codex assisted with implementation, diagnostics, and historical evidence recovery. The project's technical direction and final editorial decisions remain human-led.

LORQAI is an independent creative and technology project and is not affiliated with or endorsed by Google or OpenAI.

About the author

  • LORQAI is an independent, human-led creative universe exploring the intersection of technology, artificial intelligence, music, art and storytelling. Our technical interests include software engineering, local-first architecture, intelligent publishing systems, generative AI, automation and human-AI collaboration. Here, we share insights, practical experiments, development experiences and lessons learned while building the LORQAI ecosystem. Music Beyond Boundaries. Stories Beyond Music. Official website: https://lorqai.com

No comments yet. Be the first to comment.

LORQAI Engineering Diaries

Part 1 of 1

Real engineering experiences from LORQAI, exploring software architecture, AI-assisted development, cybersecurity, local-first applications, automation, and the lessons learned from building technology in practice.

More from this blog