Skip to content

Mashlib OIDC login requires solid-logic workaround for token exchange #13

Closed

Description

@melvincarvalho

Summary

Mashlib OIDC login does not complete without a workaround patch to solid-logic. The upstream solid-client-authn-browser library receives the OAuth authorization code but fails to exchange it for tokens.

Root Cause Analysis

The AuthCodeRedirectHandler in solid-client-authn-browser looks up session data using the OAuth state parameter:

// AuthCodeRedirectHandler.ts:91-97
const storedSessionId = await this.storageUtility.getForUser(
  oauthState,  // Uses STATE parameter as lookup key
  "sessionId",
  { errorIfNull: true }  // Throws if not found!
);

This expects localStorage to have:

  • solidClientAuthenticationUser:{state} → {sessionId: "default"}

But we observed only:

  • solidClientAuthenticationUser:default → {codeVerifier, clientId, ...}

Hypothesis: The state→sessionId mapping isn't being created during login, so the redirect handler can't find the session data.

Observable Behavior

  1. User clicks "Sign In" → redirects to IdP
  2. User logs in → redirects back with ?code=xxx&state=yyy
  3. handleIncomingRedirect() is called
  4. No POST to /idp/token - token exchange never happens
  5. session.info.isLoggedIn remains false

localStorage State After Redirect

{
  "solidClientAuthenticationUser:default": {
    "clientId": "client_xxx",
    "codeVerifier": "abc123...",
    "redirectUrl": "http://jss:4000/",
    "issuer": "http://jss:4000/"
  }
}

Missing: solidClientAuthenticationUser:{state} entry.

Workaround Implementation

Patch solid-logic/src/authn/SolidAuthnLogic.ts:

1. Capture auth code at module load (before library cleans URL)

let capturedAuthCode: { code: string, state: string } | null = null
;(function() {
  const url = new URL(window.location.href)
  const code = url.searchParams.get('code')
  const state = url.searchParams.get('state')
  if (code && state) capturedAuthCode = { code, state }
})()

2. Manual token exchange in checkUser()

// Find session data (stored under sessionId, not state)
for (key of localStorage starting with 'solidClientAuthenticationUser:') {
  if (data.codeVerifier && data.clientId) { sessionData = data; break }
}

// POST to token endpoint manually
const response = await fetch(issuer + '/idp/token', {
  method: 'POST',
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  body: new URLSearchParams({
    grant_type: 'authorization_code',
    code: capturedAuthCode.code,
    redirect_uri: sessionData.redirectUrl,
    client_id: sessionData.clientId,
    code_verifier: sessionData.codeVerifier
  })
})

3. Patch window.fetch for authenticated requests

// rdflib uses window.fetch directly, not session.fetch
const originalFetch = window.fetch
window.fetch = (input, init) => {
  if (tokens && url.startsWith(window.location.origin)) {
    init.headers.set('Authorization', 'Bearer ' + tokens.accessToken)
  }
  return originalFetch(input, init)
}

Environment

  • solid-client-authn-browser: 3.1.1
  • solid-logic: 4.0.1
  • Browser: Chrome 131
  • Server: JSS with oidc-provider

Questions

  1. Is this specific to JSS's oidc-provider, or does it affect other servers?
  2. Is the state→sessionId mapping supposed to be stored by oidc-client-ext?
  3. Has this worked historically and regressed, or is it a configuration issue?

Related

Status

  • Workaround implemented and tested
  • Root cause identified (state→sessionId mapping missing)
  • Determine if JSS-specific or general issue
  • Upstream fix pending

Activity

  1. melvincarvalho commented on Dec 29, 2025

    @melvincarvalho
    ContributorAuthor

    Deep Dive Investigation Findings

    Storage Flow Analysis

    I traced through the solid-client-authn-browser source code and confirmed the expected behavior:

    Before redirect (AuthorizationCodeWithPkceOidcHandler.setupRedirectHandler):

    await Promise.all([
      // Write 1: state → sessionId mapping
      this.storageUtility.setForUser(state, {
        sessionId: oidcLoginOptions.sessionId,
      }),
      // Write 2: sessionId → OAuth context
      this.storageUtility.setForUser(oidcLoginOptions.sessionId, {
        codeVerifier,
        issuer,
        redirectUrl,
        dpop,
        keepAlive,
      }),
    ]);
    this.redirector.redirect(targetUrl, ...);

    Both writes use setForUser without { secure: true }, so both should go to insecureStorage (BrowserStorage/localStorage).

    After redirect (AuthCodeRedirectHandler.handle):

    const storedSessionId = await this.storageUtility.getForUser(
      oauthState,  // the state from URL
      "sessionId",
      { errorIfNull: true }  // Throws if not found!
    );

    Key Finding

    The manual workaround in solid-logic successfully finds the codeVerifier entry (Write 2), which proves:

    • The second write IS persisting to localStorage
    • The data from Write 2 is available after redirect

    But the standard flow fails because:

    • The first write (state → sessionId) is NOT found in localStorage
    • Or the state value doesn't match

    Storage Utility Internals

    Both writes use the same StorageUtility.setForUser() method:

    async setForUser(userId, values, options) {
      const userData = await this.getUserData(userId, options?.secure);
      await this.setUserData(userId, { ...userData, ...values }, options?.secure);
    }

    Which calls BrowserStorage.set():

    async set(key, value) {
      this.storage.setItem(key, value);  // synchronous localStorage.setItem
    }

    Possible Root Causes

    1. Session ID Generation: When new Session() is called, it generates a random UUID. If the Session object is recreated between login and redirect handling, the sessionIds won't match. However, the state→sessionId mapping should still work if it was written.

    2. Storage Clearing: sessionInfoManager.clear() calls clearOidcPersistentStorage() which removes ALL solidClientAuthenticationUser:* keys. This is called in login() before storing new data, so shouldn't affect the current flow.

    3. Race Condition: The Promise.all should complete before redirect() is called, but there could be a subtle async issue.

    4. State Value Mismatch: The state in the redirect URL might not exactly match what was stored (encoding issues, etc.).

    Next Steps for Investigation

    1. Create a test page that logs localStorage before redirect to verify Write 1 completes
    2. Check if the state value in the redirect URL matches what should have been stored
    3. Verify the OidcClient library generates consistent state values

    Test Page Created

    I created /tmp/test-oidc-trace.html that instruments localStorage to log all writes/deletes and can be used to trace the exact flow when testing against JSS.

  2. melvincarvalho commented on Dec 29, 2025

    @melvincarvalho
    ContributorAuthor

    Resolved in v0.0.27.

    After fixing Issue #10 (CORS) and the webid claim issue, the full OIDC flow now works correctly:

    1. CORS fix (v0.0.26): Added CORS headers for all IDP endpoints
    2. WebID claim fix (v0.0.27): ID token now always includes webid claim with openid scope

    Testing confirmed:

    • State→sessionId mapping is found correctly after redirect
    • Login completes successfully: Logged in as http://jss:4000/mel/#me

    The original issue was likely caused by:

    Both solid.social and local development now work correctly with the OIDC login flow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions