### Install OpenAuth Dependencies Source: https://openauth.js.org/docs/start/standalone Installs the necessary OpenAuth and Valibot packages using Bun. ```bash bun add @openauthjs/openauth valibot ``` -------------------------------- ### Install Dependencies Source: https://openauth.js.org/docs/start/sst Installs necessary npm packages for OpenAuth, Valibot, and Hono. ```bash npm install @openauthjs/openauth valibot hono ``` -------------------------------- ### TwitchProvider Instantiation Example Source: https://openauth.js.org/docs/provider/twitch Example of how to instantiate the TwitchProvider with client ID and client secret. ```javascript TwitchProvider({ clientID: "1234567890", clientSecret: "0987654321" }) ``` -------------------------------- ### MicrosoftConfig tenant Example Source: https://openauth.js.org/docs/provider/microsoft Example of setting the tenant ID for MicrosoftConfig. ```json { tenant: "1234567890" } ``` -------------------------------- ### SST Dev Mode Output Example Source: https://openauth.js.org/docs/start/sst Example output from `npx sst dev` showing the URLs for the deployed OpenAuth server and the local Next.js app. ```text ✓ Complete MyAuth: https://fv62a3niazbkrazxheevotace40affnk.lambda-url.us-east-1.on.aws ``` -------------------------------- ### Select UI Configuration Source: https://openauth.js.org/docs/ui/select Example of how to configure the Select UI with different provider options. ```APIDOC ## POST /api/users ### Description This endpoint allows for the creation of new users in the system. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **username** (string) - Required - The desired username for the new user. - **email** (string) - Required - The email address of the new user. - **password** (string) - Required - The password for the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier for the newly created user. - **username** (string) - The username of the created user. - **email** (string) - The email address of the created user. #### Response Example ```json { "id": "user-12345", "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### KeycloakProvider Configuration Source: https://openauth.js.org/docs/provider/keycloak Example of how to configure and use the KeycloakProvider with essential parameters. ```APIDOC ## KeycloakProvider Configuration ### Description This section demonstrates the basic setup for the `KeycloakProvider` by providing the necessary configuration parameters. ### Method `KeycloakProvider(config: KeycloakConfig)` ### Endpoint N/A (Client-side configuration) ### Parameters #### Request Body - **config** (KeycloakConfig) - Required - The configuration object for the Keycloak provider. ##### KeycloakConfig Fields: - **baseUrl** (string) - Required - The base URL of the Keycloak server. - **realm** (string) - Required - The realm in the Keycloak server to authenticate against. - **clientID** (string) - Required - The client ID for your application. - **clientSecret** (string) - Optional - The client secret for your application. Should be kept secret. - **pkce** (boolean) - Optional - Defaults to `false`. Enables PKCE for the authorization code flow. - **query** (Record) - Optional - Additional parameters to pass to the authorization endpoint. - **scopes** (string[]) - Optional - A list of OAuth scopes to request. ### Request Example ```json { "baseUrl": "https://your-keycloak-domain", "realm": "your-realm", "clientID": "1234567890", "clientSecret": "0987654321" } ``` ### Response #### Success Response (Provider Instance) - **Provider** - The configured Keycloak provider instance. #### Response Example ```javascript import { KeycloakProvider } from "@openauthjs/openauth/provider/keycloak" const keycloakProvider = KeycloakProvider({ baseUrl: "https://your-keycloak-domain", realm: "your-realm", clientID: "1234567890", clientSecret: "0987654321" }) ``` ``` -------------------------------- ### Start SST Development Mode Source: https://openauth.js.org/docs/start/sst Launches SST in development mode, starting the Next.js app and the OpenAuth server concurrently. ```bash npx sst dev ``` -------------------------------- ### Start Auth Server Source: https://openauth.js.org/docs/start/standalone Starts the OpenAuth server in a separate terminal using the defined script. ```bash bun dev:auth ``` -------------------------------- ### PasswordProvider.sendCode Callback Example Source: https://openauth.js.org/docs/provider/password Example implementation of the `sendCode` callback for sending confirmation codes. ```APIDOC ## PasswordProvider.sendCode Callback Example ### Description This example demonstrates how to implement the `sendCode` callback to send a confirmation code to a user's email. ### Code Example ```javascript { sendCode: async (email, code) => { // Logic to send an email containing the 'code' to the 'email' address console.log(`Sending code ${code} to ${email}`); } } ``` ``` -------------------------------- ### PasswordProvider Configuration Source: https://openauth.js.org/docs/provider/password Configuration example for the PasswordProvider, showing how to integrate it with PasswordUI and define custom callbacks. ```APIDOC ## PasswordProvider Configuration ### Description Configures a provider that supports username and password authentication. This is usually paired with the `PasswordUI`. ### Code Example ```javascript import { PasswordUI } from "@openauthjs/openauth/ui/password" import { PasswordProvider } from "@openauthjs/openauth/provider/password" export default issuer({ providers: { password: PasswordProvider( PasswordUI({ copy: { error_email_taken: "This email is already taken." }, sendCode: (email, code) => console.log(email, code) }) ) }, // ... }) ``` ``` -------------------------------- ### CodeUI Configuration Source: https://openauth.js.org/docs/ui/code Example of how to configure the CodeUI with custom copy and a sendCode function. ```APIDOC ## POST /api/users ### Description Configures the UI that’s used by the Code provider. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **copy** (Object) - Optional - Custom copy for the UI. - **button_continue** (string) - Optional - Copy for the continue button. - **code_didnt_get** (string) - Optional - Copy for the link to resend the code. - **code_info** (string) - Optional - Copy informing that the pin code will be emailed. - **code_invalid** (string) - Optional - Error message when the code is invalid. - **code_placeholder** (string) - Optional - Copy for the pin code input. - **code_resend** (string) - Optional - Copy for the resend button. - **code_resent** (string) - Optional - Copy for when the code was resent. - **code_sent** (string) - Optional - Copy for when the code was sent. - **email_invalid** (string) - Optional - Error message when the email is invalid. - **email_placeholder** (string) - Optional - Copy for the email input. - **mode** (string) - Optional - The mode to use for the input ('email' or 'phone'). Defaults to 'email'. - **sendCode** (function) - Required - Callback to send the pin code to the user. Receives `claims` (e.g., email or phone) and `code` as arguments. ### Request Example ```json { "copy": { "code_info": "We'll send a pin code to your email" }, "sendCode": "(claims, code) => console.log(claims.email, code)" } ``` ### Response #### Success Response (200) - **CodeProviderOptions** (Object) - Options for the Code provider. #### Response Example ```json { "provider": "code" } ``` ``` -------------------------------- ### Oauth2Provider Configuration Source: https://openauth.js.org/docs/provider/oauth2 Example of how to configure and use the Oauth2Provider with essential parameters. ```APIDOC ## Oauth2Provider Configuration ### Description This section demonstrates the basic setup of the `Oauth2Provider` by providing the necessary configuration options such as `clientID`, `clientSecret`, and endpoint URLs. ### Method `Oauth2Provider(config: Oauth2Config): Provider` ### Parameters #### Request Body - **config** (Oauth2Config) - Required - Configuration object for the OAuth2 provider. ##### Oauth2Config - **clientID** (string) - Required - The client ID to identify your application. - **clientSecret** (string) - Required - The client secret for authenticating your application. This should be kept private. - **endpoint** (Object) - Required - An object containing the URLs for the authorization and token endpoints. - **authorization** (string) - Required - The URL of the authorization endpoint. - **token** (string) - Required - The URL of the token endpoint. - **jwks?** (string) - Optional - The URL of the JWKS (JSON Web Key Set) endpoint. - **pkce?** (boolean) - Optional - Whether to use PKCE (Proof Key for Code Exchange). Defaults to `false`. - **query?** (Record) - Optional - Additional query parameters to pass to the authorization endpoint. - **scopes** (string[]) - Required - An array of OAuth scopes to request. ### Request Example ```json { "clientID": "1234567890", "clientSecret": "0987654321", "endpoint": { "authorization": "https://auth.myserver.com/authorize", "token": "https://auth.myserver.com/token" }, "scopes": ["email", "profile"] } ``` ### Response #### Success Response (200) - **Provider** - The configured OAuth2 provider instance. ``` -------------------------------- ### Deploying the OpenAuth Server Source: https://openauth.js.org/docs/issuer Provides examples for deploying the Hono-based OpenAuth server to various environments like Node.js, AWS Lambda, and Bun. ```APIDOC ## Deployment Examples ### Description Examples for deploying the OpenAuth server (built with Hono) to different environments. ### Node.js Deployment ```javascript import { serve } from "@hono/node-server" import app from "./app.js" // Assuming your issuer app is exported from app.js serve(app) ``` ### AWS Lambda Deployment ```javascript import { handle } from "hono/aws-lambda" import app from "./app.js" // Assuming your issuer app is exported from app.js export const handler = handle(app) ``` ### Bun Deployment ```javascript // Assuming your issuer app is exported as default from index.js export default app ``` ### Workers Deployment ```javascript // Assuming your issuer app is exported as default from index.js export default app ``` ``` -------------------------------- ### Create and Run Next.js App Source: https://openauth.js.org/docs/start/standalone Initializes a new Next.js application and starts it in development mode. Assumes TypeScript and no ESLint. ```bash bun create next-app oa-nextjs cd oa-nextjs bun dev ``` -------------------------------- ### Initialize JumpCloudProvider Source: https://openauth.js.org/docs/provider/jumpcloud Import and initialize the JumpCloudProvider with your client ID and secret. This setup is required to use JumpCloud for authentication. ```javascript import { JumpCloudProvider } from "@openauthjs/openauth/provider/jumpcloud" export default issuer({ providers: { jumpcloud: JumpCloudProvider({ clientID: "1234567890", clientSecret: "0987654321" }) } }) ``` -------------------------------- ### PasswordProvider.validatePassword Callback Example Source: https://openauth.js.org/docs/provider/password Example implementation of the `validatePassword` callback for password validation. ```APIDOC ## PasswordProvider.validatePassword Callback Example ### Description This example shows how to implement the optional `validatePassword` callback to enforce password complexity rules. ### Code Example ```javascript { validatePassword: (password) => { if (password.length < 8) { return "Password must be at least 8 characters"; } return undefined; // Password is valid } } ``` ``` -------------------------------- ### Initiate OAuth Flow Source: https://openauth.js.org/docs/client The URL to redirect the user to. This starts the OAuth flow. For example, for SPA apps. ```javascript location.href = url ``` -------------------------------- ### OpenAuth Client Setup Source: https://openauth.js.org/docs/start/sst Initializes the OpenAuth client and defines a function to set authentication tokens in httpOnly cookies. ```typescript import { Resource } from "sst" import { createClient } from "@openauthjs/openauth/client" import { cookies as getCookies } from "next/headers" export const client = createClient({ clientID: "nextjs", issuer: Resource.MyAuth.url }) export async function setTokens(access: string, refresh: string) { const cookies = await getCookies() cookies.set({ name: "access_token", value: access, httpOnly: true, sameSite: "lax", path: "/", maxAge: 34560000, }) cookies.set({ name: "refresh_token", value: refresh, httpOnly: true, sameSite: "lax", path: "/", maxAge: 34560000, }) } ``` -------------------------------- ### GoogleProvider (OAuth2) Source: https://openauth.js.org/docs/provider/google Configuration and usage example for the GoogleProvider using OAuth2. ```APIDOC ## GoogleProvider (OAuth2) ### Description Use the `GoogleProvider` to authenticate users with Google via OAuth2. ### Method `GoogleProvider(config: GoogleConfig)` ### Parameters #### Request Body - **config** (GoogleConfig) - Required - The configuration object for the GoogleProvider. ### GoogleConfig Parameters - **clientID** (string) - Required - The client ID for your Google application. - **clientSecret** (string) - Required - The client secret for your Google application. This should be kept secret. - **pkce** (boolean) - Optional - Defaults to `false`. Enables Proof Key for Code Exchange. - **query** (Record) - Optional - Additional parameters to pass to the authorization endpoint. - **scopes** (string[]) - Optional - A list of OAuth scopes to request. ### Request Example ```javascript import { GoogleProvider } from "@openauthjs/openauth/provider/google" export default issuer({ providers: { google: GoogleProvider({ clientID: "1234567890", clientSecret: "0987654321" }) } }) ``` ### Response #### Success Response (Provider Object) - Returns a `Provider` object configured for Google OAuth2 authentication. ``` -------------------------------- ### Send Code Callback Example Source: https://openauth.js.org/docs/ui/code An example of a sendCode callback function that can be used with CodeUI. This function receives user claims and the generated code. ```javascript async (claims, code) => { // Send the code via the claim } ``` -------------------------------- ### Start Authorization Flow (PKCE Code Flow) Source: https://openauth.js.org/docs/client For SPA applications, initiate the authorization code flow with PKCE. This returns a redirect URL and a verifier challenge needed for token exchange. ```javascript const { challenge, url } = await client.authorize( redirect_uri, "code", { pkce: true } ) ``` -------------------------------- ### Select UI Provider Configuration Object Source: https://openauth.js.org/docs/ui/select An example of the configuration object for providers within the Select UI. This object maps provider names to their specific settings, such as `hide` or `display`. ```json { github: { hide: true }, google: { display: "Google" } } ``` -------------------------------- ### Implement sendCode Callback Source: https://openauth.js.org/docs/provider/password Provide a callback function for sending confirmation codes. This example logs the email and code, but should be replaced with actual email sending logic. ```javascript { sendCode: async (email, code) => { // Send an email with the code } } ``` -------------------------------- ### Configure UI Select for Providers Source: https://openauth.js.org/docs/issuer Customize the UI displayed when a user visits the OpenAuth server root URL. This example hides the GitHub provider and sets a display name for Google. ```javascript import { Select } from "@openauthjs/openauth/ui/select" issuer({ select: Select({ providers: { github: { hide: true }, google: { display: "Google" } } }) // ... }) ``` -------------------------------- ### Start Authorization Flow (Code Flow) Source: https://openauth.js.org/docs/client Initiate the authorization code flow by providing a redirect URI. This method returns a URL to redirect the user to the auth server. ```javascript const { url } = await client.authorize(redirect_uri, "code") ``` -------------------------------- ### Configure Issuer with a Single GitHub Provider Source: https://openauth.js.org/docs/issuer Example of configuring the issuer with only the GitHub provider. The key 'github' is used to identify the provider in callbacks. ```javascript import { GithubProvider } from "@openauthjs/openauth/provider/github" issuer({ providers: { github: GithubProvider() } }) ``` -------------------------------- ### Configure OpenAuth with Cloudflare KV Storage Source: https://openauth.js.org/docs/storage/cloudflare Use this snippet to initialize OpenAuth.js with the Cloudflare KV storage adapter. Ensure you have the `@openauthjs/openauth/storage/cloudflare` package installed. Replace 'my-namespace' with your actual Cloudflare KV namespace. ```javascript import { CloudflareStorage } from "@openauthjs/openauth/storage/cloudflare" const storage = CloudflareStorage({ namespace: "my-namespace" }) export default issuer({ storage, // ... }) ``` -------------------------------- ### Implement validatePassword Callback Source: https://openauth.js.org/docs/provider/password Optionally provide a callback to validate passwords during sign-up and reset. This example enforces a minimum length of 8 characters. ```javascript { validatePassword: (password) => { return password.length < 8 ? "Password must be at least 8 characters" : undefined } } ``` -------------------------------- ### Create Apple OAuth2 Provider Instance (Default) Source: https://openauth.js.org/docs/provider/apple Instantiates an Apple OAuth2 provider using the default query response mode for GET callbacks. ```javascript // Using default query response mode (GET callback) AppleProvider({ clientID: "1234567890", clientSecret: "0987654321" }) ``` -------------------------------- ### Initiate Authorization Flow Source: https://openauth.js.org/docs/client Start the OAuth authorization flow by calling the `authorize` method. This method generates a URL to redirect the user to the authorization server. ```APIDOC ## POST /authorize ### Description Start the authorization flow by generating a URL to redirect the user to the authorization server. Supports both 'code' and 'token' flows. For SPAs, the PKCE flow is recommended. ### Method POST ### Endpoint /authorize ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **redirectURI** (string) - Required - The URL to redirect the user to after authorization. - **response** (string) - Required - The type of flow, either 'code' or 'token'. - **opts** (object) - Optional - Options for the authorization flow. - **pkce** (boolean) - Optional - Enables the Proof Key for Code Exchange (PKCE) flow, recommended for SPAs. ### Request Example ```javascript // Standard code flow const redirect_uri = "https://myserver.com/callback" const { url } = await client.authorize(redirect_uri, "code") // PKCE flow for SPAs const { challenge, url } = await client.authorize( redirect_uri, "code", { pkce: true } ) ``` ### Response #### Success Response (200) - **url** (string) - The URL to redirect the user to. - **challenge** (object) - Optional - The PKCE challenge object, containing `verifier` and `challenge`, used for PKCE flow. - **verifier** (string) - The PKCE verifier. - **challenge** (string) - The PKCE challenge. #### Response Example ```json { "url": "https://auth.myserver.com/auth?client_id=...&redirect_uri=...&response_type=code&scope=...&state=...&code_challenge=...&code_challenge_method=S256" } ``` ``` -------------------------------- ### Next.js Server Actions for Authentication Source: https://openauth.js.org/docs/start/sst Implement server actions for user authentication, login initiation, and logout. The `auth` action verifies the user's session, `login` starts the OAuth flow, and `logout` clears session tokens. ```typescript "use server" import { redirect } from "next/navigation" import { headers as getHeaders, cookies as getCookies } from "next/headers" import { subjects } from "../auth/subjects" import { client, setTokens } from "./auth" export async function auth() { const cookies = await getCookies() const accessToken = cookies.get("access_token") const refreshToken = cookies.get("refresh_token") if (!accessToken) { return false } const verified = await client.verify(subjects, accessToken.value, { refresh: refreshToken?.value, }) if (verified.err) { return false } if (verified.tokens) { await setTokens(verified.tokens.access, verified.tokens.refresh) } return verified.subject } export async function login() { const cookies = await getCookies() const accessToken = cookies.get("access_token") const refreshToken = cookies.get("refresh_token") if (accessToken) { const verified = await client.verify(subjects, accessToken.value, { refresh: refreshToken?.value, }) if (!verified.err && verified.tokens) { await setTokens(verified.tokens.access, verified.tokens.refresh) redirect("/") } } const headers = await getHeaders() const host = headers.get("host") const protocol = host?.includes("localhost") ? "http" : "https" const { url } = await client.authorize(`${protocol}://${host}/api/callback`, "code") redirect(url) } export async function logout() { const cookies = await getCookies() cookies.delete("access_token") cookies.delete("refresh_token") redirect("/") } ``` -------------------------------- ### Initiate Authorization Code Flow with PKCE (SPA/Mobile) Source: https://openauth.js.org/docs Starts the OAuth authorization code flow with Proof Key for Code Exchange (PKCE) for single-page applications or mobile apps. Stores the PKCE challenge in local storage. ```javascript const { challenge, url } = await client.authorize(, "code", { pkce: true }) localStorage.setItem("challenge", JSON.stringify(challenge)) location.href = url ``` -------------------------------- ### Implement Custom sendCode Callback Source: https://openauth.js.org/docs/provider/code Provides an example implementation for the sendCode callback within CodeProviderConfig. This callback is designed to handle sending the generated code via email or phone number based on the provided claims. ```javascript { sendCode: async (claims, code) => { // Send the code through the email or phone number based on the claims } } ``` -------------------------------- ### Initialize XProvider with Configuration Source: https://openauth.js.org/docs/provider/x Use this snippet to set up the XProvider for X.com authentication. Ensure you replace placeholder clientID and clientSecret with your actual credentials. ```javascript import { XProvider } from "@openauthjs/openauth/provider/x" export default issuer({ providers: { x: XProvider({ clientID: "1234567890", clientSecret: "0987654321" }) } }) ``` -------------------------------- ### XProvider Initialization Source: https://openauth.js.org/docs/provider/x Demonstrates how to initialize the XProvider with client ID and client secret. ```APIDOC ## XProvider Initialization ### Description Initializes the XProvider for X.com authentication using your application's client ID and client secret. ### Method `XProvider(config)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { XProvider } from "@openauthjs/openauth/provider/x" export default issuer({ providers: { x: XProvider({ clientID: "1234567890", clientSecret: "0987654321" }) } }) ``` ### Response #### Success Response (200) Returns a configured X.com OAuth2 provider. #### Response Example ```json { "provider": "XProvider" } ``` ``` -------------------------------- ### Initialize SpotifyProvider Source: https://openauth.js.org/docs/provider/spotify Import and initialize the SpotifyProvider with your client ID and client secret. ```javascript import { SpotifyProvider } from "@openauthjs/openauth/provider/spotify" export default issuer({ providers: { spotify: SpotifyProvider({ clientID: "1234567890", clientSecret: "0987654321" }) } }) ``` -------------------------------- ### MemoryStorage Initialization Source: https://openauth.js.org/docs/storage/memory Demonstrates how to initialize the MemoryStorage adapter and use it with OpenAuth. ```APIDOC ## MemoryStorage Initialization ### Description Configure OpenAuth to use a simple in-memory store. This is useful for testing and development. It’s not meant to be used in production. ### Method ```javascript import { MemoryStorage } from "@openauthjs/openauth/storage/memory" const storage = MemoryStorage() export default issuer({ storage, // ... }) ``` ``` -------------------------------- ### Initialize GithubProvider Source: https://openauth.js.org/docs/provider/github Use this to authenticate with Github. Ensure you have the correct clientID and clientSecret. ```javascript import { GithubProvider } from "@openauthjs/openauth/provider/github" export default issuer({ providers: { github: GithubProvider({ clientID: "1234567890", clientSecret: "0987654321" }) } }) ``` -------------------------------- ### Initialize YahooProvider with Configuration Source: https://openauth.js.org/docs/provider/yahoo Use this provider to authenticate with Yahoo. It requires clientID and clientSecret for app identification and authentication. ```javascript import { YahooProvider } from "@openauthjs/openauth/provider/yahoo" export default issuer({ providers: { yahoo: YahooProvider({ clientID: "1234567890", clientSecret: "0987654321" }) } }) ``` -------------------------------- ### Initialize DiscordProvider Source: https://openauth.js.org/docs/provider/discord Use this provider to authenticate with Discord. Requires clientID and clientSecret. ```javascript import { DiscordProvider } from "@openauthjs/openauth/provider/discord" export default issuer({ providers: { discord: DiscordProvider({ clientID: "1234567890", clientSecret: "0987654321" }) } }) ``` -------------------------------- ### GoogleOidcProvider (OIDC) Source: https://openauth.js.org/docs/provider/google Configuration and usage example for the GoogleOidcProvider using OpenID Connect. ```APIDOC ## GoogleOidcProvider (OIDC) ### Description Use the `GoogleOidcProvider` to authenticate users with Google via OpenID Connect. This is useful for verifying user email addresses. ### Method `GoogleOidcProvider(config: GoogleOidcConfig)` ### Parameters #### Request Body - **config** (GoogleOidcConfig) - Required - The configuration object for the GoogleOidcProvider. ### GoogleOidcConfig Parameters - **clientID** (string) - Required - The client ID for your Google application. - **query** (Record) - Optional - Additional parameters to pass to the authorization endpoint. - **scopes** (string[]) - Optional - A list of OIDC scopes to request. ### Request Example ```javascript import { GoogleOidcProvider } from "@openauthjs/openauth/provider/google" export default issuer({ providers: { google: GoogleOidcProvider({ clientID: "1234567890" }) } }) ``` ### Response #### Success Response (Provider Object) - Returns a `Provider` object configured for Google OIDC authentication. ``` -------------------------------- ### Initialize KeycloakProvider Source: https://openauth.js.org/docs/provider/keycloak Use this provider to authenticate with a Keycloak server. Ensure you have the necessary import statement. ```javascript import { KeycloakProvider } from "@openauthjs/openauth/provider/keycloak" export default issuer({ providers: { keycloak: KeycloakProvider({ baseUrl: "https://your-keycloak-domain", realm: "your-realm", clientID: "1234567890", clientSecret: "0987654321" }) } }) ``` -------------------------------- ### Import Issuer Function Source: https://openauth.js.org/docs Import the core `issuer` function from the `@openauthjs/openauth` package to start building your authentication server. ```javascript import { issuer } from "@openauthjs/openauth" ``` -------------------------------- ### Initialize SlackProvider Source: https://openauth.js.org/docs/provider/slack Use this to configure and initialize the Slack provider for authentication. Ensure all required parameters like team, clientID, and clientSecret are provided. ```javascript import { SlackProvider } from "@openauthjs/openauth/provider/slack" export default issuer({ providers: { slack: SlackProvider({ team: "T1234567890", clientID: "1234567890", clientSecret: "0987654321", scopes: ["openid", "email", "profile"] }) } }) ``` -------------------------------- ### Initiate OAuth Flow Source: https://openauth.js.org/docs/client Start the OAuth 2.0 authorization code flow. This generates a URL to redirect the user to the authorization server. ```javascript const redirect_uri = "https://myserver.com/callback" const { url } = await client.authorize( redirect_uri, "code" ) ``` -------------------------------- ### Create OpenAuth Server Directory Source: https://openauth.js.org/docs/start/standalone Creates a directory to house the OpenAuth server-side logic. ```bash mkdir auth ``` -------------------------------- ### Create Auth Directory Source: https://openauth.js.org/docs/start/sst Creates a directory to house the OpenAuth server code. ```bash mkdir auth ``` -------------------------------- ### Enable PKCE Flow Source: https://openauth.js.org/docs/client Enable the PKCE flow. This is for SPA apps. ```javascript { pkce: true } ``` -------------------------------- ### Adding Authentication Providers Source: https://openauth.js.org/docs/issuer Demonstrates how to configure various authentication providers like GitHub and email/password for the OpenAuth server. ```APIDOC ## POST /api/providers ### Description Configures authentication providers for the OpenAuth server, such as GitHub or email/password. ### Method POST ### Endpoint /api/providers ### Parameters #### Request Body - **providers** (Record) - Required - An object where keys are provider names and values are provider configurations. - **github** (GithubProvider) - Example provider configuration for GitHub. - **password** (PasswordProvider) - Example provider configuration for email/password. ### Request Example ```json { "providers": { "github": "GithubProvider({\"clientId\": \"YOUR_CLIENT_ID\", \"clientSecret\": \"YOUR_CLIENT_SECRET\"})", "password": "PasswordProvider({\"credentials\": \"YOUR_CREDENTIALS_ADAPTER\"})" } } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating providers have been added. #### Response Example ```json { "message": "Providers configured successfully." } ``` ``` -------------------------------- ### Initialize SST Source: https://openauth.js.org/docs/start/sst Initializes SST in an existing Next.js project. Selects AWS as the target environment. ```bash npx sst@latest init ``` -------------------------------- ### Set Token TTL Values Source: https://openauth.js.org/docs/issuer Configure the time-to-live (TTL) for access and refresh tokens in seconds. This example sets a 30-day access token and a 1-year refresh token. ```javascript { ttl: { access: 60 * 60 * 24 * 30, refresh: 60 * 60 * 24 * 365 } } ``` -------------------------------- ### Create X.com OAuth2 Provider Source: https://openauth.js.org/docs/provider/x This demonstrates the basic instantiation of the XProvider with essential configuration parameters. ```javascript XProvider({ clientID: "1234567890", clientSecret: "0987654321" }) ``` -------------------------------- ### Handle OAuth Success Callback Source: https://openauth.js.org/docs/issuer Define the success callback for OAuth flows. This example logs the provider and tokenset for GitHub, and email for password-based authentication, then sets a user subject. ```javascript { success: async (ctx, value) => { let userID if (value.provider === "password") { console.log(value.email) userID = ... // lookup user or create them } if (value.provider === "github") { console.log(value.tokenset.access) userID = ... // lookup user or create them } return ctx.subject("user", { userID }) }, // ... } ``` -------------------------------- ### Initiate Authorization Code Flow (SSR) Source: https://openauth.js.org/docs Starts the OAuth authorization code flow for server-side rendered applications. This redirects the user to the authorization server to log in and grant permissions. ```javascript const { url } = await client.authorize( "", "code" ) ``` -------------------------------- ### Configure GitHub Provider Source: https://openauth.js.org/docs Set up the GitHub provider for authentication. This requires client ID, client secret, and desired scopes. Ensure these are securely stored in environment variables. ```javascript import { GithubProvider } from "@openauthjs/openauth/provider/github" const app = issuer({ providers: { github: GithubProvider({ clientID: process.env.GITHUB_CLIENT_ID!, clientSecret: process.env.GITHUB_CLIENT_SECRET!, scopes: ["user:email"], }), }, // ... }) ``` -------------------------------- ### Configure Issuer with Multiple Providers Source: https://openauth.js.org/docs/issuer Demonstrates how to configure the issuer to support multiple authentication providers, such as GitHub and Google. ```javascript { providers: { github: GithubProvider(), google: GoogleProvider() } } ``` -------------------------------- ### Deploy App to AWS with SST Source: https://openauth.js.org/docs/start/sst Use this command to deploy your application to AWS. Specify a stage name, such as 'production', for your deployment. ```bash npx sst deploy --stage production ``` -------------------------------- ### SpotifyProvider Constructor Source: https://openauth.js.org/docs/provider/spotify Create a Spotify OAuth2 provider instance using the SpotifyProvider function and its configuration. ```javascript SpotifyProvider({ clientID: "1234567890", clientSecret: "0987654321" }) ``` -------------------------------- ### Creating a Custom Theme Source: https://openauth.js.org/docs/ui/theme This snippet demonstrates how to define and use a completely custom theme object. ```APIDOC ## Creating a Custom Theme ### Description Define your own custom theme object to control the appearance of OpenAuth.js. ### Method ```javascript import type { Theme } from "@openauthjs/openauth/ui/theme" const MY_THEME: Theme = { title: "Acne", radius: "none", favicon: "https://www.example.com/favicon.svg", // ... } export default issuer({ theme: MY_THEME, // ... }) ``` ``` -------------------------------- ### Create Next.js App Source: https://openauth.js.org/docs/start/sst Initializes a new Next.js application. Assumes TypeScript and no ESLint. ```bash npx create-next-app@latest oa-nextjs cd oa-nextjs ``` -------------------------------- ### Create an OpenAuth Issuer Source: https://openauth.js.org/docs/issuer Initialize an OpenAuth server using the `issuer` function. This requires defining providers, storage, subjects, and a success callback. ```javascript import { issuer } from "@openauthjs/openauth" const app = issuer({ providers: { ... }, storage, subjects, success: async (ctx, value) => { ... } }) ``` -------------------------------- ### Initialize Issuer with Basic Configuration Source: https://openauth.js.org/docs Initialize the OpenAuth issuer function with essential configuration including providers, storage, subjects, and a success callback. ```javascript const app = issuer({ providers: { ... }, storage, subjects, success: async (ctx, value) => { ... } }) ``` -------------------------------- ### XProviderConfig Parameters Source: https://openauth.js.org/docs/provider/x Details the configuration options available for the XProvider. ```APIDOC ## XProviderConfig Parameters ### Description Configuration options for the XProvider. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### XProviderConfig Fields - **clientID** (string) - Required - The client ID for your X.com application. - **clientSecret** (string) - Required - The client secret for your X.com application. This should be kept secret. - **pkce** (boolean) - Optional - Defaults to `false`. Enables Proof Key for Code Exchange (PKCE), which is required by some providers like X.com. - **query** (Record) - Optional - Additional parameters to pass to the authorization endpoint. - **scopes** (string[]) - Required - A list of OAuth scopes to request for the user. ### Example Usage ```javascript XProvider({ clientID: "my-client", clientSecret: "0987654321", pkce: true, query: { access_type: "offline", prompt: "consent" }, scopes: ["email", "profile"] }) ``` ``` -------------------------------- ### MemoryStorage with Persistence Source: https://openauth.js.org/docs/storage/memory Shows how to configure the MemoryStorage adapter to persist its data to a JSON file. ```APIDOC ## MemoryStorage with Persistence ### Description Optionally, you can persist the store to a file. ### Method ```javascript MemoryStorage({ persist: "./persist.json" }) ``` ``` -------------------------------- ### Import and Configure OidcProvider Source: https://openauth.js.org/docs/provider/oidc Import the OidcProvider and configure it within the issuer function. This sets up the authentication flow with a specified client ID and issuer URL. ```javascript import { OidcProvider } from "@openauthjs/openauth/provider/oidc" export default issuer({ providers: { oauth2: OidcProvider({ clientId: "1234567890", issuer: "https://auth.myserver.com" }) } }) ``` -------------------------------- ### Add Auth Server Script to package.json Source: https://openauth.js.org/docs/start/standalone Adds a script to `package.json` for running the OpenAuth server with hot-reloading on port 3001. ```json "dev:auth": "PORT=3001 bun run --hot auth/index.ts", ``` -------------------------------- ### OpenAuth Server Implementation Source: https://openauth.js.org/docs/start/sst Sets up the OpenAuth server using Hono and various OpenAuth modules. Includes a basic user retrieval function and email code sending. ```typescript import { handle } from "hono/aws-lambda" import { issuer } from "@openauthjs/openauth" import { CodeUI } from "@openauthjs/openauth/ui/code" import { CodeProvider } from "@openauthjs/openauth/provider/code" import { MemoryStorage } from "@openauthjs/openauth/storage/memory" import { subjects } from "./subjects" async function getUser(email: string) { // Get user from database and return user ID return "123" } const app = issuer({ subjects, storage: MemoryStorage(), // Remove after setting custom domain allow: async () => true, providers: { code: CodeProvider( CodeUI({ sendCode: async (email, code) => { console.log(email, code) }, }), ), }, success: async (ctx, value) => { if (value.provider === "code") { return ctx.subject("user", { id: await getUser(value.claims.email) }) } throw new Error("Invalid provider") }, }) export const handler = handle(app) ``` -------------------------------- ### Configure Google Provider with OIDC Source: https://openauth.js.org/docs/provider/google Set up Google authentication using the OpenID Connect (OIDC) flow. This is useful for verifying user email addresses. Only the client ID is required. ```javascript import { GoogleOidcProvider } from "@openauthjs/openauth/provider/google" export default issuer({ providers: { google: GoogleOidcProvider({ clientID: "1234567890" }) } }) ``` -------------------------------- ### Client Initialization Source: https://openauth.js.org/docs/client Initialize the OpenAuth client with your application's client ID and the authorization server's issuer URL. ```APIDOC ## Client Initialization ### Description Initialize the OpenAuth client with your application's client ID and the authorization server's issuer URL. ### Request Body - **clientID** (string) - Required - Your application's unique client identifier. - **issuer** (string) - Required - The URL of the authorization server. ### Request Example ```javascript import { createClient } from "@openauthjs/openauth/client" const client = createClient({ clientID: "my-client", issuer: "https://auth.myserver.com" }) ``` ### Response - **Client** - An instance of the OpenAuth client. ``` -------------------------------- ### SpotifyProvider Configuration Source: https://openauth.js.org/docs/provider/spotify Configuration options for the SpotifyProvider. ```APIDOC ## SpotifyProvider ### Description Use this provider to authenticate with Spotify. ### Method `SpotifyProvider(config)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### `config` (`SpotifyConfig`) The config for the provider. **Returns** `Provider` Create a Spotify OAuth2 provider. ### SpotifyConfig * `clientID` (string) - Required - The client ID. This is just a string to identify your app. * `clientSecret` (string) - Required - The client secret. This is a private key that’s used to authenticate your app. It should be kept secret. * `pkce` (boolean) - Optional - Default: false - Whether to use PKCE (Proof Key for Code Exchange) for the authorization code flow. Some providers like x.com require this. * `query` (Record) - Optional - Any additional parameters that you want to pass to the authorization endpoint. * `scopes` (string[]) - Required - A list of OAuth scopes that you want to request. ### Request Example ```json { "clientID": "1234567890", "clientSecret": "0987654321", "scopes": ["email", "profile"], "pkce": true, "query": { "access_type": "offline", "prompt": "consent" } } ``` ### Response #### Success Response (200) This section is not applicable as this is a configuration object. #### Response Example None ``` -------------------------------- ### Configure Memory Storage for Testing Source: https://openauth.js.org/docs Utilize `MemoryStorage` for testing purposes. For production environments, consider using persistent storage solutions like DynamoDB or Cloudflare KV. ```javascript import { MemoryStorage } from "@openauthjs/openauth/storage/memory" const app = issuer({ providers: { ... }, subjects, async success(ctx, value) { ... }, storage: MemoryStorage(), }) ``` -------------------------------- ### Using Built-in Themes Source: https://openauth.js.org/docs/ui/theme This snippet shows how to apply one of the pre-defined themes provided by OpenAuth.js. ```APIDOC ## Using Built-in Themes ### Description Apply a pre-defined theme to your OpenAuth.js integration. ### Method ```javascript import { THEME_SST } from "@openauthjs/openauth/ui/theme" export default issuer({ theme: THEME_SST, // ... }) ``` ``` -------------------------------- ### SlackProvider Configuration Source: https://openauth.js.org/docs/provider/slack Configuration options for the SlackProvider. ```APIDOC ## SlackProvider Reference doc for the `SlackProvider`. Use this provider to authenticate with Slack. ```javascript import { SlackProvider } from "@openauthjs/openauth/provider/slack" export default issuer({ providers: { slack: SlackProvider({ team: "T1234567890", clientID: "1234567890", clientSecret: "0987654321", scopes: ["openid", "email", "profile"] }) } }) ``` ## SlackProvider ```javascript SlackProvider(config) ``` ### Parameters * `config` `SlackConfig` The config for the provider. **Returns** `Provider` Creates a Slack OAuth2 provider. ```javascript SlackProvider({ team: "T1234567890", clientID: "1234567890", clientSecret: "0987654321", scopes: ["openid", "email", "profile"] }) ``` ## SlackConfig * `clientID` `string` * `clientSecret` `string` * `pkce?` `boolean` * `query?` `Record``<``string`, `string``>` * `scopes` `(``“``email``”`` | ``“``profile``”`` | ``“``openid``”``)[]` * `team` `string` #### SlackConfig.clientID **Type** `string` The client ID. This is just a string to identify your app. ```json { "clientID": "my-client" } ``` #### SlackConfig.clientSecret **Type** `string` The client secret. This is a private key that’s used to authenticate your app. It should be kept secret. ```json { "clientSecret": "0987654321" } ``` #### SlackConfig.pkce? **Type** `boolean` **Default** false Whether to use PKCE (Proof Key for Code Exchange) for the authorization code flow. Some providers like x.com require this. #### SlackConfig.query? **Type** `Record``<``string`, `string``>` Any additional parameters that you want to pass to the authorization endpoint. ```json { "query": { "access_type": "offline", "prompt": "consent" } } ``` #### SlackConfig.scopes **Type** `(``“``email``”`` | ``“``profile``”`` | ``“``openid``”``)[]` The scopes to request from the user. Scope| Description ---|--- `email`| Grants permission to access the user’s email address. `profile`| Grants permission to access the user’s profile information. `openid`| Grants permission to use OpenID Connect to verify the user’s identity. #### SlackConfig.team **Type** `string` The workspace the user is intending to authenticate. If that workspace has been previously authenticated, the user will be signed in directly, bypassing the consent screen. ``` -------------------------------- ### Configure CodeProvider with Default CodeUI Source: https://openauth.js.org/docs/provider/code Sets up the CodeProvider with a default CodeUI, customizing the copy for code information and defining a sendCode callback to log the email and code. ```javascript import { CodeUI } from "@openauthjs/openauth/ui/code" import { CodeProvider } from "@openauthjs/openauth/provider/code" export default issuer({ providers: { code: CodeProvider( CodeUI({ copy: { code_info: "We'll send a pin code to your email" }, sendCode: (claims, code) => console.log(claims.email, code) }) ) }, // ... }) ``` -------------------------------- ### MemoryStorage Options Source: https://openauth.js.org/docs/storage/memory Details the options available for configuring the MemoryStorage adapter. ```APIDOC ## MemoryStorage Options ### Description Configuration options for the MemoryStorage adapter. ### Method ```javascript MemoryStorage(input?) ``` ### Parameters #### Path Parameters * `input?` (`MemoryStorageOptions`) - Optional - Configuration options for the memory store. ### Returns `StorageAdapter` ## MemoryStorageOptions ### Description Options to configure the memory store. ### Fields #### `persist` (string) - Optional Optionally, backup the store to a file. So it’ll be persisted when the issuer restarts. ### Example ```json { "persist": "./persist.json" } ``` ``` -------------------------------- ### Configure GithubProvider clientSecret Source: https://openauth.js.org/docs/provider/github Set the clientSecret to authenticate your application. This should be kept secret. ```javascript { clientSecret: "0987654321" } ``` -------------------------------- ### SpotifyConfig: clientSecret Source: https://openauth.js.org/docs/provider/spotify Configure the SpotifyProvider with your application's client secret. This should be kept private. ```javascript { clientSecret: "0987654321" } ```