### Run Browser Example App Source: https://github.com/inrupt/solid-client-authn-js/blob/main/README.md Clone the repository, install dependencies, navigate to the browser example directory, install its dependencies, and start the development server. ```bash git clone https://github.com/inrupt/solid-client-authn-js cd solid-client-authn-js npm ci cd packages/browser/examples/single/bundle/ npm ci npm run start ``` -------------------------------- ### Install solid-client-authn-browser Source: https://github.com/inrupt/solid-client-authn-js/blob/main/README.md Install the latest stable version of solid-client-authn-browser for browser-based applications. ```bash npm install @inrupt/solid-client-authn-browser ``` -------------------------------- ### Install solid-client-authn-node Source: https://github.com/inrupt/solid-client-authn-js/blob/main/README.md Install the latest stable version of solid-client-authn-node for server-side and console-based applications. ```bash npm install @inrupt/solid-client-authn-node ``` -------------------------------- ### Install Browser and Node.js Packages Source: https://context7.com/inrupt/solid-client-authn-js/llms.txt Install the appropriate package for your environment. Use `@inrupt/solid-client-authn-browser` for web applications and `@inrupt/solid-client-authn-node` for server-side or console applications. ```bash # For browser-based projects npm install @inrupt/solid-client-authn-browser # For Node.js-based projects npm install @inrupt/solid-client-authn-node ``` -------------------------------- ### Install Documentation Requirements Source: https://github.com/inrupt/solid-client-authn-js/blob/main/packages/browser/docs/api/README.md Install the Python packages required for building the HTML documentation. This command fetches requirements from a remote URL. ```sh pip install -r https://raw.githubusercontent.com/inrupt/docs-assets/main/requirements/api/requirements.txt ``` -------------------------------- ### Run Development Server Source: https://github.com/inrupt/solid-client-authn-js/blob/main/e2e/browser/solid-client-authn-browser/test-app/README.md Use these commands to start the Next.js development server. Access the application at http://localhost:3000. ```bash npm run dev # or yarn dev ``` -------------------------------- ### Install Inrupt Solid JS Libraries for Browser Source: https://github.com/inrupt/solid-client-authn-js/blob/main/README.md Install the necessary Inrupt Solid JavaScript libraries for browser-based projects, including solid-client, solid-client-authn-browser, and vocab-common-rdf. ```bash # For browser-based projects npm install @inrupt/solid-client @inrupt/solid-client-authn-browser @inrupt/vocab-common-rdf ``` -------------------------------- ### Install Inrupt Solid JS Libraries for Node.js Source: https://github.com/inrupt/solid-client-authn-js/blob/main/README.md Install the necessary Inrupt Solid JavaScript libraries for Node.js-based projects, including solid-client, solid-client-authn-node, and vocab-common-rdf. ```bash # For Node.js-based projects npm install @inrupt/solid-client @inrupt/solid-client-authn-node @inrupt/vocab-common-rdf ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/inrupt/solid-client-authn-js/blob/main/packages/browser/docs/api/README.md Use this command to create a Python virtual environment for isolating project dependencies. Activate it before installing packages. ```sh python3 -m venv source /bin/activate ``` -------------------------------- ### Generate API .md Files Source: https://github.com/inrupt/solid-client-authn-js/blob/main/packages/browser/docs/api/README.md Run this command to generate the necessary API markdown files. Ensure Node.js is installed and dependencies are managed by npm. ```sh npm ci; npm run build-api-docs ``` -------------------------------- ### Browser Script Tag Usage Example Source: https://context7.com/inrupt/solid-client-authn-js/llms.txt Include the bundled library via a script tag for direct HTML usage. Handles session restoration, login, logout, and error events. ```html Solid App

Solid Authentication Demo

Not logged in
``` -------------------------------- ### Node.js: Session Restoration from Tokens Source: https://context7.com/inrupt/solid-client-authn-js/llms.txt Create an authenticated session directly from a stored token set, useful for clustered deployments and session restoration. This example shows how to restore and refresh tokens. ```typescript import { Session, refreshTokens, EVENTS, SessionTokenSet } from "@inrupt/solid-client-authn-node"; // Restore session from stored tokens async function restoreSession(storedTokens: SessionTokenSet, sessionId: string) { const session = await Session.fromTokens(storedTokens, sessionId); if (session.info.isLoggedIn) { console.log(`Session restored for ${session.info.webId}`); // Use the authenticated session const response = await session.fetch("https://pod.example.com/private/data"); return response; } return null; } // Refresh tokens before they expire async function refreshAndUseSession(storedTokens: SessionTokenSet, sessionId: string) { // Refresh the tokens const refreshedTokens = await refreshTokens(storedTokens); // Save refreshed tokens to storage await saveTokensToDatabase(sessionId, refreshedTokens); // Create session with refreshed tokens const session = await Session.fromTokens(refreshedTokens, sessionId); if (session.info.isLoggedIn) { return session; } throw new Error("Failed to refresh session"); } // Example: Express route using stored tokens app.get("/fetch", async (req, res) => { const storedTokens = await getTokensFromDatabase(req.session.sessionId); const session = await Session.fromTokens(storedTokens, req.session.sessionId); if (!session.info.isLoggedIn) { return res.status(401).send("Session expired, please login again"); } const response = await session.fetch(req.query.resource); const data = await response.text(); res.send(data); }); ``` -------------------------------- ### Node.js: Authorization Code Flow (Web Apps) Source: https://context7.com/inrupt/solid-client-authn-js/llms.txt Implement the authorization code flow with redirect handling for web applications. This example uses Express and cookie-session for managing sessions. Ensure to replace placeholder values with your actual configuration. ```typescript import { Session, EVENTS } from "@inrupt/solid-client-authn-node"; import express from "express"; import cookieSession from "cookie-session"; const app = express(); app.use(cookieSession({ keys: ["secret-key"] })); // In-memory session cache (use database in production) const sessionCache = {}; app.get("/login", async (req, res) => { const session = new Session({ keepAlive: false }); req.session.sessionId = session.info.sessionId; // Capture auth state for handling redirect session.events.on(EVENTS.AUTHORIZATION_REQUEST, (authState) => { sessionCache[session.info.sessionId] = authState; }); await session.login({ oidcIssuer: "https://login.inrupt.com", redirectUrl: "http://localhost:3000/redirect", clientId: "https://myapp.example.com/clientid", handleRedirect: (url) => res.redirect(url) }); }); app.get("/redirect", async (req, res) => { const authState = sessionCache[req.session.sessionId]; if (!authState) { return res.status(401).send("No auth state found"); } // Restore session from auth state const session = await Session.fromAuthorizationRequestState( authState, req.session.sessionId ); // Capture new tokens for future use session.events.on(EVENTS.NEW_TOKENS, (tokenSet) => { sessionCache[session.info.sessionId] = tokenSet; }); // Complete the login flow const fullUrl = `${req.protocol}://${req.get("host")}${req.originalUrl}`; await session.handleIncomingRedirect(fullUrl); if (session.info.isLoggedIn) { res.send(`Logged in as ${session.info.webId}`); } else { res.status(400).send("Login failed"); } }); app.listen(3000); ``` -------------------------------- ### Node.js: Session Initialization and Configuration Source: https://context7.com/inrupt/solid-client-authn-js/llms.txt Demonstrates creating a Session instance in Node.js with different storage options and configurations, including default in-memory storage, custom storage, and disabling auto-refresh for scripts. ```typescript import { Session, EVENTS, getSessionFromStorage, getSessionIdFromStorageAll, clearSessionFromStorageAll, InMemoryStorage } from "@inrupt/solid-client-authn-node"; // Create a session with default in-memory storage const session = new Session(); // Create a session with custom storage const customStorage = new InMemoryStorage(); // Or implement IStorage interface const sessionWithStorage = new Session({ storage: customStorage }); // Create a session that doesn't auto-refresh (for scripts) const scriptSession = new Session({ keepAlive: false }); // Session information console.log(session.info.sessionId); console.log(session.info.isLoggedIn); console.log(session.info.webId); console.log(session.info.expirationDate); // Event listeners session.events.on(EVENTS.LOGIN, () => { console.log(`Logged in as ${session.info.webId}`); }); session.events.on(EVENTS.NEW_TOKENS, (tokenSet) => { // Store tokens for later use (e.g., in database for clustered deployments) console.log("New tokens received:", tokenSet); saveToDatabase(session.info.sessionId, tokenSet); }); session.events.on(EVENTS.AUTHORIZATION_REQUEST, (authState) => { // Capture auth state for clustered deployments console.log("Auth state:", authState); saveAuthStateToDatabase(session.info.sessionId, authState); }); ``` -------------------------------- ### Build HTML Documentation Source: https://github.com/inrupt/solid-client-authn-js/blob/main/packages/browser/docs/api/README.md Execute this command to compile the API documentation into HTML format. The output will be located in the 'build/html' directory. ```sh make html ``` -------------------------------- ### Browser: Handle Incoming Redirect and Initiate Login Source: https://context7.com/inrupt/solid-client-authn-js/llms.txt Handle the incoming redirect from an Identity Provider to complete the login process, optionally restoring a previous session. Initiate login by redirecting the user to the OIDC issuer. ```typescript import { Session, EVENTS } from "@inrupt/solid-client-authn-browser"; const session = new Session(); // Handle incoming redirect on page load (must be called first) async function handlePageLoad() { const sessionInfo = await session.handleIncomingRedirect({ url: window.location.href, restorePreviousSession: true // Auto-restore session on refresh }); if (sessionInfo?.isLoggedIn) { console.log(`Welcome back, ${sessionInfo.webId}!`); return sessionInfo; } return null; } // Initiate login (redirects user away from app) async function loginUser() { await session.login({ oidcIssuer: "https://login.inrupt.com", // Identity Provider URL redirectUrl: "http://localhost:3000/callback", // Your app's callback URL clientId: "https://app.example.com/clientid", // Optional: Client ID Document URL clientName: "My Solid App", // Optional: Human-readable name tokenType: "DPoP", // Default: "DPoP", or "Bearer" customScopes: ["profile", "email"] // Optional: Additional OIDC scopes }); // Note: This promise never resolves as the user is redirected } // Complete example with page initialization (async () => { const sessionInfo = await handlePageLoad(); if (!sessionInfo?.isLoggedIn) { // Show login button, which calls loginUser() when clicked document.getElementById("loginBtn").onclick = loginUser; } else { // User is logged in, show authenticated content document.getElementById("webid").textContent = sessionInfo.webId; } })(); ``` -------------------------------- ### Handle Incoming Redirect and Initiate Login with Solid Client AuthN JS Source: https://github.com/inrupt/solid-client-authn-js/blob/main/packages/browser/examples/single/script/index.html When the page loads, this code checks for an incoming redirect from the Identity Provider (IdP). If no session is active, it initiates the login process. Otherwise, it displays the WebID of the logged-in user. ```javascript const session = new solidClientAuthentication.Session(); // When loading the page, check if you are being redirected from the IdP session .handleIncomingRedirect(window.location.href) .then((sessionInfo) => { if(!sessionInfo.isLoggedIn) { // If you are not logged in, initiate the login session.login({ redirectUrl: "http://localhost:3001/", oidcIssuer: document.getElementById("oidcIssuer").innerHTML, }); } else { // The page was loaded after a redirect from the IdP document.getElementById("WebId").innerHTML = sessionInfo.webId; } }); ``` -------------------------------- ### Solid Client Authn Core API Source: https://github.com/inrupt/solid-client-authn-js/blob/main/packages/core/docs/api/redirects.txt This section provides an overview of the core functionalities and interfaces available in the solid-client-authn-js library. ```APIDOC ## Solid Client Authn Core API Overview ### Description This API provides the core functionalities for authenticating with Solid Pods using the solid-client-authn-js library. It includes interfaces for managing user sessions, handling authentication flows (like OIDC), and interacting with storage mechanisms. ### Interfaces #### `ISessionInfo` Represents information about the current user session. #### `ILoginInputOptions` Defines the options available when initiating a login process. #### `IStorage` An interface for defining storage mechanisms to persist authentication-related data. #### `IStorageUtility` Provides utility functions for interacting with storage, potentially abstracting underlying implementations. #### `IIssuerConfigFetcher` An interface for fetching configuration details from an OIDC issuer. ### Modules - **`@inrupt/solid-client-authn-core`**: The main module containing the core authentication logic and interfaces. - **`_sessioninfo`**: Contains the `ISessionInfo` interface. - **`_ilogininputoptions`**: Contains the `ILoginInputOptions` interface. - **`_storage`**: Contains interfaces and implementations related to storage, including `IStorage` and `IStorageUtility`. - **`_login/oidc`**: Handles OpenID Connect specific authentication flows. - **`_util`**: Contains utility functions for schema validation and handler patterns. ### Usage Examples While specific endpoint examples are not detailed here, the library is typically used to: 1. Initialize an authentication context. 2. Initiate a login flow using `ILoginInputOptions`. 3. Retrieve session information via `ISessionInfo`. 4. Interact with storage using `IStorage` and `IStorageUtility`. ``` -------------------------------- ### Browser Session Class Initialization and Events Source: https://context7.com/inrupt/solid-client-authn-js/llms.txt Initialize a Session instance or use the default session. Register event listeners for login, logout, session restoration, expiration, and errors. Access session information like WebID and login status. ```typescript import { Session, EVENTS, getDefaultSession, login, logout, fetch, handleIncomingRedirect } from "@inrupt/solid-client-authn-browser"; // Create a new session instance const session = new Session(); // Or use the default session with top-level functions const defaultSession = getDefaultSession(); // Check session information console.log(session.info.sessionId); // Unique session identifier console.log(session.info.isLoggedIn); // Boolean login status console.log(session.info.webId); // User's WebID (when logged in) // Register event listeners session.events.on(EVENTS.LOGIN, () => { console.log(`Logged in as ${session.info.webId}`); }); session.events.on(EVENTS.LOGOUT, () => { console.log("User logged out"); }); session.events.on(EVENTS.SESSION_RESTORED, (currentUrl) => { console.log(`Session restored, was at: ${currentUrl}`); }); session.events.on(EVENTS.SESSION_EXPIRED, () => { console.log("Session has expired"); }); session.events.on(EVENTS.ERROR, (error, errorDescription) => { console.error(`Authentication error: ${error}`, errorDescription); }); ``` -------------------------------- ### Login Input Options Source: https://github.com/inrupt/solid-client-authn-js/blob/main/packages/browser/docs/api/redirects.txt Defines the input options for the login method. ```APIDOC ## ILoginInputOptions Interface ### Description Defines the input options for the login method, specifying how to authenticate the user. ### Fields - `oidcIssuer` (string): The URL of the OpenID Connect issuer. - `clientName` (string, optional): The name of the client application. - `handleRedirect` (function, optional): A callback function to handle the OIDC redirect. - `storage` (IStorage, optional): An instance of an IStorage implementation for session persistence. ``` -------------------------------- ### Implement Custom Session Storage Source: https://context7.com/inrupt/solid-client-authn-js/llms.txt Create a custom storage solution by implementing the IStorage interface for persistent session data. This allows integration with various backends like Redis or databases. ```typescript import { IStorage, Session } from "@inrupt/solid-client-authn-node"; // Custom storage implementation class RedisStorage implements IStorage { private client: any; // Your Redis client constructor(redisClient: any) { this.client = redisClient; } async get(key: string): Promise { const value = await this.client.get(key); return value ?? undefined; } async set(key: string, value: string): Promise { await this.client.set(key, value); } async delete(key: string): Promise { await this.client.del(key); } } // Use custom storage with Session const redisStorage = new RedisStorage(redisClient); const session = new Session({ storage: redisStorage }); // Use with multi-session functions import { getSessionFromStorage } from "@inrupt/solid-client-authn-node"; const storedSession = await getSessionFromStorage(sessionId, { storage: redisStorage }); ``` -------------------------------- ### Node.js: Client Credentials Login for Scripts Source: https://context7.com/inrupt/solid-client-authn-js/llms.txt Authenticates a Node.js session using client credentials, suitable for automated scripts. Requires environment variables for the OpenID Provider, client ID, and client secret. Always logs out to prevent the Node.js process from hanging. ```typescript import { Session } from "@inrupt/solid-client-authn-node"; async function runAuthenticatedScript() { const session = new Session({ keepAlive: false }); // Login with client credentials (no redirect needed) await session.login({ oidcIssuer: process.env.OPENID_PROVIDER, // e.g., "https://login.inrupt.com" clientId: process.env.CLIENT_ID, // From static registration clientSecret: process.env.CLIENT_SECRET // From static registration }); if (session.info.isLoggedIn) { console.log(`Logged in as ${session.info.webId}`); // Perform authenticated operations const response = await session.fetch("https://pod.example.com/private/data"); const data = await response.text(); console.log("Fetched data:", data); } // Always logout to clean up (prevents Node.js from hanging) await session.logout(); } runAuthenticatedScript().catch(console.error); ``` -------------------------------- ### Browser: Authenticated Fetch Source: https://context7.com/inrupt/solid-client-authn-js/llms.txt Use the session's fetch method to make authenticated requests to Solid resources. Ensure the user is logged in before fetching private data. Custom headers and methods are supported. ```typescript import { Session } from "@inrupt/solid-client-authn-browser"; const session = new Session(); // After successful login... async function fetchPrivateData() { if (!session.info.isLoggedIn) { throw new Error("Must be logged in to fetch private resources"); } // Fetch a private resource from the user's Pod const response = await session.fetch("https://pod.example.com/private/data.ttl"); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } const data = await response.text(); console.log("Fetched data:", data); return data; } // Fetch with custom headers and options async function postData(resourceUrl, content) { const response = await session.fetch(resourceUrl, { method: "PUT", headers: { "Content-Type": "text/turtle" }, body: content }); if (!response.ok) { throw new Error(`Failed to save: ${response.status}`); } return response; } // Using the default session's fetch import { fetch as authenticatedFetch } from "@inrupt/solid-client-authn-browser"; const response = await authenticatedFetch("https://pod.example.com/profile/card"); ``` -------------------------------- ### Node.js: Manage Multiple User Sessions Source: https://context7.com/inrupt/solid-client-authn-js/llms.txt Use storage-based session retrieval for managing multiple user sessions in server applications. Configure auto-login using stored refresh tokens or manually refresh when needed. Supports listing and clearing all stored sessions. ```typescript import { getSessionFromStorage, getSessionIdFromStorageAll, clearSessionFromStorageAll, refreshSession, InMemoryStorage } from "@inrupt/solid-client-authn-node"; // Use a shared storage for all sessions const storage = new InMemoryStorage(); // Retrieve a session from storage and log it in async function getSession(sessionId: string) { const session = await getSessionFromStorage(sessionId, { storage, refreshSession: true // Auto-login using stored refresh token }); if (session && session.info.isLoggedIn) { console.log(`Retrieved session for ${session.info.webId}`); return session; } return null; } // Get a session without auto-login async function getSessionNoRefresh(sessionId: string) { const session = await getSessionFromStorage(sessionId, { storage, refreshSession: false // Don't auto-login }); if (session) { // Manually refresh when needed await refreshSession(session, { storage }); return session; } return null; } // List all stored sessions async function listAllSessions() { const sessionIds = await getSessionIdFromStorageAll(storage); console.log(`Found ${sessionIds.length} sessions:`, sessionIds); return sessionIds; } // Clear all sessions from storage async function clearAllSessions() { await clearSessionFromStorageAll(storage); console.log("All sessions cleared"); } // Handle new refresh token callback async function getSessionWithTokenCallback(sessionId: string) { const session = await getSessionFromStorage(sessionId, { storage, onNewRefreshToken: (newToken) => { console.log("New refresh token issued, save to external storage if needed"); } }); return session; } ``` -------------------------------- ### Storage Interface Source: https://github.com/inrupt/solid-client-authn-js/blob/main/packages/browser/docs/api/redirects.txt Defines the interface for session storage mechanisms. ```APIDOC ## IStorage Interface ### Description Defines the interface for session storage mechanisms, allowing for persistence of authentication tokens and session data. ### Methods - `get(key: string)`: Retrieves a value from storage. - `set(key: string, value: string)`: Stores a key-value pair. - `delete(key: string)`: Removes a key-value pair from storage. ``` -------------------------------- ### Session API Source: https://github.com/inrupt/solid-client-authn-js/blob/main/packages/browser/docs/api/redirects.txt Provides methods for managing user sessions, including login, logout, and retrieving session information. ```APIDOC ## Session API ### Description Provides methods for managing user sessions, including login, logout, and retrieving session information. ### Endpoint `/api/javascript/solid-client-authn-browser/classes/_session_.session.html` ### Methods - `login(options: ILoginInputOptions)`: Initiates the login process. - `logout()`: Ends the current user session. - `getWebId()`: Retrieves the WebID of the currently logged-in user. - `getSessionInfo()`: Returns information about the current session. ### Interfaces - `ISessionOptions`: Options for configuring a session. - `ISessionInfo`: Information about an active session. ``` -------------------------------- ### Handle Session Lifecycle Events Source: https://context7.com/inrupt/solid-client-authn-js/llms.txt Listen to various session events such as login, logout, expiration, and errors. Ensure authentication errors are handled to prevent issues. ```typescript import { Session, EVENTS, SessionTokenSet, AuthorizationRequestState } from "@inrupt/solid-client-authn-node"; const session = new Session(); // Login event - fired after successful authentication session.events.on(EVENTS.LOGIN, () => { console.log(`User logged in: ${session.info.webId}`); }); // Logout event - fired after logout session.events.on(EVENTS.LOGOUT, () => { console.log("User logged out"); }); // Session expired - fired when the access token expires session.events.on(EVENTS.SESSION_EXPIRED, () => { console.log("Session expired, refresh required"); }); // Session extended - fired when tokens are refreshed session.events.on(EVENTS.SESSION_EXTENDED, (expiresIn: number) => { console.log(`Session extended, expires in ${expiresIn} seconds`); }); // Session restored (browser only) - fired after silent re-authentication session.events.on(EVENTS.SESSION_RESTORED, (previousUrl: string) => { console.log(`Session restored, was at: ${previousUrl}`); }); // Error - fired on authentication errors (must be handled!) session.events.on(EVENTS.ERROR, (error: string | null, description?: string | Error | null) => { console.error(`Auth error: ${error}`, description); }); // New tokens - fired when tokens are issued or refreshed session.events.on(EVENTS.NEW_TOKENS, (tokenSet: SessionTokenSet) => { console.log("Tokens received:", { accessToken: tokenSet.accessToken?.substring(0, 20) + "...", idToken: tokenSet.idToken?.substring(0, 20) + "...", refreshToken: tokenSet.refreshToken ? "present" : "none", expiresAt: tokenSet.expiresAt, webId: tokenSet.webId, issuer: tokenSet.issuer, clientId: tokenSet.clientId }); }); // Authorization request (Node.js) - fired during auth code flow session.events.on(EVENTS.AUTHORIZATION_REQUEST, (state: AuthorizationRequestState) => { console.log("Auth state for clustered deployment:", { codeVerifier: state.codeVerifier.substring(0, 10) + "...", state: state.state, issuer: state.issuer, redirectUrl: state.redirectUrl, dpopBound: state.dpopBound, clientId: state.clientId }); }); // One-time listener session.events.once(EVENTS.LOGIN, () => { console.log("First login event"); }); // Remove listener const logoutHandler = () => console.log("Logout"); session.events.on(EVENTS.LOGOUT, logoutHandler); session.events.off(EVENTS.LOGOUT, logoutHandler); ``` -------------------------------- ### Browser: IDP Logout Source: https://context7.com/inrupt/solid-client-authn-js/llms.txt Initiates a full logout by redirecting the user to their Identity Provider. Requires specifying a post-logout redirect URL and optionally a state parameter. ```typescript import { Session } from "@inrupt/solid-client-authn-browser"; const session = new Session(); // IDP logout (redirects user to Identity Provider for full logout) async function fullLogout() { await session.logout({ logoutType: "idp", // URL to redirect after logout (must be in Client ID Document) postLogoutUrl: "https://myapp.example.com/logged-out", // Optional state to include in redirect state: "custom-state-value" }); // User is redirected to Identity Provider } ``` -------------------------------- ### Node.js: Perform Token-Based Logout Source: https://context7.com/inrupt/solid-client-authn-js/llms.txt Perform RP-initiated logout using stored tokens without needing a full Session object. This includes handling redirects for IDP logout or silently validating and invalidating tokens. ```typescript import { logout } from "@inrupt/solid-client-authn-node"; // Express.js logout endpoint app.get("/logout", async (req, res) => { const storedTokens = sessionCache[req.session.sessionId]; if (!storedTokens) { return res.status(400).send("No active session"); } // Clear local session data delete sessionCache[req.session.sessionId]; // Perform IDP logout with redirect await logout( storedTokens, (url) => res.redirect(url), // Redirect handler "http://localhost:3000/" // Post-logout redirect URL ); }); // Logout without redirect (just validate and invalidate) async function logoutSilently(storedTokens) { try { await logout( storedTokens, () => {}, // No-op redirect handler undefined // No post-logout URL ); console.log("Logged out successfully"); } catch (error) { console.error("Logout failed:", error.message); } } ``` -------------------------------- ### SessionManager API Source: https://github.com/inrupt/solid-client-authn-js/blob/main/packages/browser/docs/api/redirects.txt Manages multiple user sessions and provides methods for creating, retrieving, and deleting sessions. ```APIDOC ## SessionManager API ### Description Manages multiple user sessions and provides methods for creating, retrieving, and deleting sessions. ### Endpoint `/api/javascript/solid-client-authn-browser/classes/_sessionmanager_.sessionmanager.html` ### Methods - `login(options: ILoginInputOptions)`: Creates or retrieves an existing session. - `logout(webId: string)`: Ends a specific user session. - `get(webId: string)`: Retrieves a session by its WebID. - `getAll()`: Returns all active sessions. ### Interfaces - `ISessionManagerOptions`: Options for configuring the SessionManager. ``` -------------------------------- ### Error Handling Source: https://github.com/inrupt/solid-client-authn-js/blob/main/packages/node/docs/api/redirects.txt Details on error types, specifically NotImplementedError. ```APIDOC ## NotImplementedError Class ### Description An error indicating that a requested feature or method has not been implemented. ### Usage This error is typically thrown when attempting to use functionality that is not yet available in the library or a specific implementation. ``` -------------------------------- ### Handler handle method Source: https://github.com/inrupt/solid-client-authn-js/blob/main/ARCHITECTURE.md This method actually processes the request. It is invoked when canHandle() returns true. ```typescript handle(request) ``` -------------------------------- ### Session Management API Source: https://github.com/inrupt/solid-client-authn-js/blob/main/packages/node/docs/api/redirects.txt Provides access to the Session and SessionManager classes for handling user authentication and session lifecycle. ```APIDOC ## Session Class ### Description Represents an authenticated session with a Solid Pod. ### Methods - `login(options)`: Initiates the login process. - `logout()`: Terminates the current session. - `getWebID()`: Retrieves the WebID of the authenticated user. ### Properties - `isLoggedIn`: Boolean indicating if the user is currently logged in. ## SessionManager Class ### Description Manages multiple authenticated sessions. ### Methods - `login(webId, options)`: Logs in a user with the provided WebID. - `logout(webId)`: Logs out the user associated with the given WebID. - `get(webId)`: Retrieves the session for a specific WebID. - `getAll()`: Returns all active sessions. ### Events - `sessionCreated`: Emitted when a new session is created. - `sessionDestroyed`: Emitted when a session is destroyed. ## ISessionOptions Interface ### Description Options for configuring a Solid session. ### Properties - `oidcIssuer`: The OIDC issuer URL. - `clientName`: The name of the client application. - `redirectUrl`: The URL to redirect to after authentication. ``` -------------------------------- ### Browser: App-Only Logout Source: https://context7.com/inrupt/solid-client-authn-js/llms.txt Performs an app-only logout, which clears the local session data without redirecting the user. This is useful for single-page applications where a full redirect is not desired. ```typescript import { Session } from "@inrupt/solid-client-authn-browser"; const session = new Session(); // App-only logout (clears local session, does not redirect) async function appLogout() { await session.logout({ logoutType: "app" }); console.log("Logged out of application"); // session.info.isLoggedIn is now false } ``` -------------------------------- ### Handler canHandle method Source: https://github.com/inrupt/solid-client-authn-js/blob/main/ARCHITECTURE.md This method declares the handler's ability to handle a given request. It returns a boolean. ```typescript canHandle(request) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.