diff --git a/demo/nextjs/lib/auth.ts b/demo/nextjs/lib/auth.ts index dbd9b03c..c23a2123 100644 --- a/demo/nextjs/lib/auth.ts +++ b/demo/nextjs/lib/auth.ts @@ -21,6 +21,7 @@ import { createPool } from "mysql2/promise"; import { nextCookies } from "better-auth/next-js"; import { passkey } from "better-auth/plugins/passkey"; import { stripe } from "@better-auth/stripe"; +import { sso } from "@better-auth/sso"; import { Stripe } from "stripe"; const from = process.env.BETTER_AUTH_EMAIL || "delivered@resend.dev"; @@ -182,7 +183,6 @@ export const auth = betterAuth({ multiSession(), oAuthProxy(), nextCookies(), - oneTap(), customSession(async (session) => { return { @@ -238,6 +238,111 @@ export const auth = betterAuth({ }, }, }), + sso({ + defaultSSO: [ + { + domain: "http://localhost:3000", + providerId: "sso", + samlConfig: { + issuer: "http://localhost:3001/api/sso/saml2/sp/metadata", + entryPoint: "http://localhost:3001/api/sso/saml2/sp/acs", + cert: `-----BEGIN CERTIFICATE----- + MIIDBzCCAe+gAwIBAgIUCLBK4f75EXEe4gyroYnVaqLoSp4wDQYJKoZIhvcNAQEL + BQAwEzERMA8GA1UEAwwIZHVtbXlpZHAwHhcNMjQwNTEzMjE1NDE2WhcNMzQwNTEx + MjE1NDE2WjATMREwDwYDVQQDDAhkdW1teWlkcDCCASIwDQYJKoZIhvcNAQEBBQAD + ggEPADCCAQoCggEBAKhmgQmWb8NvGhz952XY4SlJlpWIK72RilhOZS9frDYhqWVJ + HsGH9Z7sSzrM/0+YvCyEWuZV9gpMeIaHZxEPDqW3RJ7KG51fn/s/qFvwctf+CZDj + yfGDzYs+XIgf7p56U48EmYeWpB/aUW64gSbnPqrtWmVFBisOfIx5aY3NubtTsn+g + 0XbdX0L57+NgSvPQHXh/GPXA7xCIWm54G5kqjozxbKEFA0DS3yb6oHRQWHqIAM/7 + mJMdUVZNIV1q7c2JIgAl23uDWq+2KTE2R5liP/KjvjwKonVKtTqGqX6ei25rsTHO + aDpBH/LdQK2txgsm7R7+IThWNvUI0Tttr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ryhL/b+ttKKqVeT87XYDkvVhlSSSVAKcCwK/UU6z8Ty9dODUkd93Qsbof8fGMlXeYCtDHMRanvWLtk4wVkAMyNkDYHzJ1FbO7v44ZBbqNzSLy2kosbRELlcz+P3/42xumlDqAw/k13tWUdlLDxb0pd8R5yBev6HkIdJBIWtKmUuI+e8F/yTNf5kY7HO1p0NeKdVeZw4Ydw33+BwVxVNmhIxzdP5ZFQv0XRFWhCMo/6RLEepCvWUp/T1WRFqgwAdURaQrvvfpjO/Ls+neht1SWDeP8RRgsDrXIc3gZfaD8q4liIDTZ6HsFi7FmLbZatU8jJ4pCstxQLCvmix+1zF6Fwa9V5OApSTbVqBOsDZbJxeAoSzy5Wx28wufAZT4Kc/OaViXPV5o/ordPs4EYKgd/eNFCgIsZYXe75rYXqnieAIfJEGddsLBpqlgLkwvf5KVS4QNqqX+2YubP63y+3sICq2ScdhO3LZs3nlqQ/SgMiJnCBbDUDZ9GGgJNJVVytcSz5IDQHeflrq/zTt1c4q1DO3CS7mimAnTCjetERRQ3mgY/2hRiuCDFj3Cy7QMjFs3vBsbWrjNWlqyveFmHDRkq34Om7eA2jl3LZ5u7vSm0/ylp/vtoysMjwEmw/0NA3hZPTG3OJxcvFcXBsz0SiFcd1U= + + + + + urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress + + + + + Organization Name + Organization DisplayName + http://localhost:3000/ + + + Technical Contact Name + technical_contact@gmail.com + + + Support Contact Name + support_contact@gmail.com + + + `, + }, + idpMetadata: { + entityURL: + "https://dummyidp.com/apps/app_01k16v4vb5yytywqjjvv2b3435/metadata", + entityID: + "https://dummyidp.com/apps/app_01k16v4vb5yytywqjjvv2b3435/metadata", + redirectURL: + "https://dummyidp.com/apps/app_01k16v4vb5yytywqjjvv2b3435/sso", + singleSignOnService: [ + { + Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect", + Location: + "https://dummyidp.com/apps/app_01k16v4vb5yytywqjjvv2b3435/sso", + }, + ], + cert: `-----BEG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+ -----END CERTIFICATE-----`, + }, + callbackUrl: "/dashboard", + }, + }, + ], + }), deviceAuthorization({ expiresIn: "3min", interval: "5s", diff --git a/demo/nextjs/package.json b/demo/nextjs/package.json index 5d5837b3..cde215ff 100644 --- a/demo/nextjs/package.json +++ b/demo/nextjs/package.json @@ -12,6 +12,7 @@ }, "dependencies": { "@better-auth/stripe": "workspace:*", + "@better-auth/sso": "workspace:*", "@better-fetch/fetch": "catalog:", "@hookform/resolvers": "^5.2.1", "@libsql/client": "^0.15.14", diff --git a/docs/components/sidebar-content.tsx b/docs/components/sidebar-content.tsx index 45c27745..32a9ee46 100644 --- a/docs/components/sidebar-content.tsx +++ b/docs/components/sidebar-content.tsx @@ -2166,6 +2166,21 @@ C0.7,239.6,62.1,0.5,62.2,0.4c0,0,54,13.8,119.9,30.8S302.1,62,302.2,62c0.2,0,0.2, ), }, + { + title: "SAML SSO with Okta", + href: "/docs/guides/saml-sso-with-okta", + icon: () => ( + + + + ), + }, { title: "Optimize for Performance", href: "/docs/guides/optimizing-for-performance", diff --git a/docs/content/docs/guides/saml-sso-with-okta.mdx b/docs/content/docs/guides/saml-sso-with-okta.mdx new file mode 100644 index 00000000..f31750ee --- /dev/null +++ b/docs/content/docs/guides/saml-sso-with-okta.mdx @@ -0,0 +1,174 @@ +--- +title: SAML SSO with Okta +description: A guide to integrating SAML Single Sign-On (SSO) with Better Auth, featuring Okta +--- + +This guide walks you through setting up SAML Single Sign-On (SSO) with your Identity Provider (IdP), using Okta as an example. For advanced configuration details and the full API reference, check out the [SSO Plugin Documentation](/docs/plugins/sso). + +## What is SAML? + +SAML (Security Assertion Markup Language) is an XML-based standard for exchanging authentication and authorization data between an Identity Provider (IdP) (e.g., Okta, Azure AD, OneLogin) and a Service Provider (SP) (in this case, Better Auth). + +In this setup: + +- **IdP (Okta)**: Authenticates users and sends assertions about their identity. +- **SP (Better Auth)**: Validates assertions and logs the user in.up. + +### Step 1: Create a SAML Application in Okta + +1. Log in to your Okta Admin Console +2. Navigate to Applications > Applications +3. Click "Create App Integration" +4. Select "SAML 2.0" as the Sign-in method +5. Configure the following settings: + + - **Single Sign-on URL**: Your Better Auth ACS endpoint (e.g., `http://localhost:3000/api/auth/sso/saml2/sp/acs/sso`). while `sso` being your providerId + - **Audience URI (SP Entity ID)**: Your Better Auth metadata URL (e.g., `http://localhost:3000/api/auth/sso/saml2/sp/metadata`) + - **Name ID format**: Email Address or any of your choice. + +6. Download the IdP metadata XML file and certificate + +### Step 2: Configure Better Auth + +Here’s an example configuration for Okta in a dev environment: + +```typescript +const ssoConfig = { + defaultSSO: [{ + domain: "localhost:3000", // Your domain + providerId: "sso", + samlConfig: { + // SP Configuration + issuer: "http://localhost:3000/api/auth/sso/saml2/sp/metadata", + entryPoint: "https://trial-1076874.okta.com/app/trial-1076874_samltest_1/exktofb0a62hqLAUL697/sso/saml", + callbackUrl: "/dashboard", // Redirect after successful authentication + + // IdP Configuration + idpMetadata: { + entityID: "https://trial-1076874.okta.com/app/exktofb0a62hqLAUL697/sso/saml/metadata", + singleSignOnService: [{ + Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect", + Location: "https://trial-1076874.okta.com/app/trial-1076874_samltest_1/exktofb0a62hqLAUL697/sso/saml" + }], + cert: `-----BEGIN CERTIFICATE----- +MIIDqjCCApKgAwIBAgIGAZhVGMeUMA0GCSqGSIb3DQEBCwUAMIGVMQswCQYDVQQGEwJVUzETMBEG +... +[Your Okta Certificate] +... +-----END CERTIFICATE-----` + }, + + // SP Metadata + spMetadata: { + metadata: ` + ... + [Your SP Metadata XML] + ... + ` + } + } + }] +} +``` + +### Step 3: Multiple Default Providers (Optional) + +You can configure multiple SAML providers for different domains: + +```typescript +const ssoConfig = { + defaultSSO: [ + { + domain: "company.com", + providerId: "company-okta", + samlConfig: { + // Okta SAML configuration for company.com + } + }, + { + domain: "partner.com", + providerId: "partner-adfs", + samlConfig: { + // ADFS SAML configuration for partner.com + } + }, + { + domain: "contractor.org", + providerId: "contractor-azure", + samlConfig: { + // Azure AD SAML configuration for contractor.org + } + } + ] +} +``` + + +**Explicit**: Pass providerId directly when signing in. +**Domain fallback:** Matches based on the user’s email domain. e.g. user@company.com → matches `company-okta` provider. + + + +### Step 4: Initiating Sign-In + +You can start an SSO flow in three ways: + +**1. Explicitly by `providerId` (recommended):** + +```typescript +// Explicitly specify which provider to use +await authClient.signIn.sso({ + providerId: "company-okta", + callbackURL: "/dashboard" +}); +``` + +**2. By email domain matching:** + +```typescript +// Automatically matches provider based on email domain +await authClient.signIn.sso({ + email: "user@company.com", + callbackURL: "/dashboard" +}); +``` + +**3. By specifying domain:** + +```typescript +// Explicitly specify domain for matching +await authClient.signIn.sso({ + domain: "partner.com", + callbackURL: "/dashboard" +}); +``` + +**Important Notes**: + - DummyIDP should ONLY be used for development and testing + - Never use these certificates in production + - The example uses `localhost:3000` - adjust URLs for your environment + - For production, always use proper IdP providers like Okta, Azure AD, or OneLogin + +### Step 5: Dynamically Registering SAML Providers + +For dynamic registration, you should register SAML providers using the API. See the [SSO Plugin Documentation](/docs/plugins/sso#register-a-saml-provider) for detailed registration instructions. + +Example registration: + +```typescript +await authClient.sso.register({ + providerId: "okta-prod", + issuer: "https://your-domain.com", + domain: "your-domain.com", + samlConfig: { + // Your production SAML configuration + } +}); +``` + +## Additional Resources + +- [SSO Plugin Documentation](/docs/plugins/sso) +- [Okta SAML Documentation](https://developer.okta.com/docs/concepts/saml/) +- [SAML 2.0 Specification](https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf) diff --git a/docs/content/docs/plugins/sso.mdx b/docs/content/docs/plugins/sso.mdx index 722a54be..53e08f1b 100644 --- a/docs/content/docs/plugins/sso.mdx +++ b/docs/content/docs/plugins/sso.mdx @@ -7,11 +7,6 @@ description: Integrate Single Sign-On (SSO) with your application. Single Sign-On (SSO) allows users to authenticate with multiple applications using a single set of credentials. This plugin supports OpenID Connect (OIDC), OAuth2 providers, and SAML 2.0. - - -This plugin is in active development and may not be suitable for production use. Please report any issues or bugs on [GitHub](https://github.com/better-auth/better-auth) and any security concerns on [security@better-auth.com](mailto:security@better-auth.com). - - ## Installation @@ -100,14 +95,18 @@ await authClient.sso.register({ discoveryEndpoint: "https://idp.example.com/.well-known/openid-configuration", scopes: ["openid", "email", "profile"], pkce: true, - }, - mapping: { - id: "sub", - email: "email", - emailVerified: "email_verified", - name: "name", - image: "picture", - }, + mapping: { + id: "sub", + email: "email", + emailVerified: "email_verified", + name: "name", + image: "picture", + extraFields: { + department: "department", + role: "role" + } + } + } }); ``` @@ -129,14 +128,18 @@ await auth.api.registerSSOProvider({ discoveryEndpoint: "https://idp.example.com/.well-known/openid-configuration", scopes: ["openid", "email", "profile"], pkce: true, - }, - mapping: { - id: "sub", - email: "email", - emailVerified: "email_verified", - name: "name", - image: "picture", - }, + mapping: { + id: "sub", + email: "email", + emailVerified: "email_verified", + name: "name", + image: "picture", + extraFields: { + department: "department", + role: "role" + } + } + } }, headers, }); @@ -183,19 +186,20 @@ await authClient.sso.register({ isAssertionEncrypted: true, encPrivateKey: "-----BEGIN RSA PRIVATE KEY-----\n...\n-----END RSA PRIVATE KEY-----", encPrivateKeyPass: "your-sp-encryption-key-password" + }, + mapping: { + id: "nameID", + email: "email", + name: "displayName", + firstName: "givenName", + lastName: "surname", + emailVerified: "email_verified", + extraFields: { + department: "department", + role: "role" + } } - }, - mapping: { - id: "nameID", - email: "email", - name: "displayName", - firstName: "givenName", - lastName: "surname", - extraFields: { - department: "department", - role: "role" - } - }, + } }); ``` @@ -233,19 +237,20 @@ await auth.api.registerSSOProvider({ isAssertionEncrypted: true, encPrivateKey: "-----BEGIN RSA PRIVATE KEY-----\n...\n-----END RSA PRIVATE KEY-----", encPrivateKeyPass: "your-sp-encryption-key-password" + }, + mapping: { + id: "nameID", + email: "email", + name: "displayName", + firstName: "givenName", + lastName: "surname", + emailVerified: "email_verified", + extraFields: { + department: "department", + role: "role" + } } - }, - mapping: { - id: "nameID", - email: "email", - name: "displayName", - firstName: "givenName", - lastName: "surname", - extraFields: { - department: "department", - role: "role" - } - }, + } }, headers, }); @@ -611,6 +616,36 @@ organizationProvisioning: { ## SAML Configuration + +### Default SSO Provider + +```ts title="auth.ts" +const auth = betterAuth({ + plugins: [ + sso({ + defaultSSO: { + providerId: "default-saml", // Provider ID for the default provider + samlConfig: { + issuer: "https://your-app.com", + entryPoint: "https://idp.example.com/sso", + cert: "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----", + callbackUrl: "http://localhost:3000/api/auth/sso/saml2/sp/acs", + spMetadata: { + entityID: "http://localhost:3000/api/auth/sso/saml2/sp/metadata", + metadata: "", + } + } + } + }) + ] +}); +``` + +The defaultSSO provider will be used when: +1. No matching provider is found in the database + +This allows you to test SAML authentication without setting up providers in the database. The defaultSSO provider supports all the same configuration options as regular SAML providers. + ### Service Provider Configuration When registering a SAML provider, you need to provide Service Provider (SP) metadata configuration: @@ -679,6 +714,8 @@ The plugin requires additional fields in the `ssoProvider` table to store the pr ]} /> +For a detailed guide on setting up SAML SSO with examples for Okta and testing with DummyIDP, see our [SAML SSO Setup Guide](/docs/guides/sso-saml-guide). + ## Options ### Server @@ -735,5 +772,31 @@ The plugin requires additional fields in the `ssoProvider` table to store the pr type: "number | function", default: 10, }, + defaultSSO: { + description: "Configure a default SSO provider for testing and development. This provider will be used when no matching provider is found in the database.", + type: "object", + properties: { + domain: { + description: "The domain to match for this default provider.", + type: "string", + required: true, + }, + providerId: { + description: "The provider ID to use for the default provider.", + type: "string", + required: true, + }, + samlConfig: { + description: "SAML configuration for the default provider.", + type: "SAMLConfig", + required: false, + }, + oidcConfig: { + description: "OIDC configuration for the default provider.", + type: "OIDCConfig", + required: false, + }, + }, + }, }} /> diff --git a/packages/sso/CHANGELOG.md b/packages/sso/CHANGELOG.md deleted file mode 100644 index dc9254aa..00000000 --- a/packages/sso/CHANGELOG.md +++ /dev/null @@ -1,20 +0,0 @@ -# @better-auth/sso - -## 1.3.4 - -### Patch Changes - -- 2bd2fa9: Added support for listing organization members with pagination, sorting, and filtering, and improved client inference for additional organization fields. Also fixed date handling in rate limits and tokens, improved Notion OAuth user extraction, and ensured session is always set in context. - - Organization - - - Added listMembers API with pagination, sorting, and filtering. - - Added membersLimit param to getFullOrganization. - - Improved client inference for additional fields in organization schemas. - - Bug Fixes - - Fixed date handling by casting DB values to Date objects before using date methods. - - Fixed Notion OAuth to extract user info correctly. - - Ensured session is set in context when reading from cookie cach - -- Updated dependencies [2bd2fa9] - - better-auth@1.3.4 diff --git a/packages/sso/src/index.ts b/packages/sso/src/index.ts index 3d5d7a7c..09d23dde 100644 --- a/packages/sso/src/index.ts +++ b/packages/sso/src/index.ts @@ -24,6 +24,7 @@ import { decodeJwt } from "jose"; import { setSessionCookie } from "better-auth/cookies"; import type { FlowResult } from "samlify/types/src/flow"; import { XMLValidator } from "fast-xml-parser"; +import type { IdentityProvider } from "samlify/types/src/entity-idp"; const fastValidator = { async validate(xml: string) { @@ -37,6 +38,25 @@ const fastValidator = { saml.setSchemaValidator(fastValidator); +export interface OIDCMapping { + id?: string; + email?: string; + emailVerified?: string; + name?: string; + image?: string; + extraFields?: Record; +} + +export interface SAMLMapping { + id?: string; + email?: string; + emailVerified?: string; + name?: string; + firstName?: string; + lastName?: string; + extraFields?: Record; +} + export interface OIDCConfig { issuer: string; pkce: boolean; @@ -50,30 +70,49 @@ export interface OIDCConfig { tokenEndpoint?: string; tokenEndpointAuthentication?: "client_secret_post" | "client_secret_basic"; jwksEndpoint?: string; - mapping?: { - id?: string; - email?: string; - emailVerified?: string; - name?: string; - image?: string; - extraFields?: Record; - }; + mapping?: OIDCMapping; } export interface SAMLConfig { issuer: string; entryPoint: string; - signingKey: string; - certificate: string; - attributeConsumingServiceIndex: number; - mapping?: { - id?: string; - email?: string; - name?: string; - firstName?: string; - lastName?: string; - extraFields?: Record; + cert: string; + callbackUrl: string; + audience?: string; + idpMetadata?: { + metadata?: string; + entityID?: string; + entityURL?: string; + redirectURL?: string; + cert?: string; + privateKey?: string; + privateKeyPass?: string; + isAssertionEncrypted?: boolean; + encPrivateKey?: string; + encPrivateKeyPass?: string; + singleSignOnService?: Array<{ + Binding: string; + Location: string; + }>; }; + spMetadata: { + metadata?: string; + entityID?: string; + binding?: string; + privateKey?: string; + privateKeyPass?: string; + isAssertionEncrypted?: boolean; + encPrivateKey?: string; + encPrivateKeyPass?: string; + }; + wantAssertionsSigned?: boolean; + signatureAlgorithm?: string; + digestAlgorithm?: string; + identifierFormat?: string; + privateKey?: string; + decryptionPvk?: string; + additionalParams?: Record; + mapping?: SAMLMapping; } export interface SSOProvider { @@ -132,6 +171,29 @@ export interface SSOOptions { provider: SSOProvider; }) => Promise<"member" | "admin">; }; + /** + * Default SSO provider configurations for testing. + * These will take the precedence over the database providers. + */ + defaultSSO?: Array<{ + /** + * The domain to match for this default provider. + * This is only used to match incoming requests to this default provider. + */ + domain: string; + /** + * The provider ID to use + */ + providerId: string; + /** + * SAML configuration + */ + samlConfig?: SAMLConfig; + /** + * OIDC configuration + */ + oidcConfig?: OIDCConfig; + }>; /** * Override user info with the provider info. * @default false @@ -284,6 +346,37 @@ export const sso = (options?: SSOOptions) => { }) .default(true) .optional(), + mapping: z + .object({ + id: z.string({}).meta({ + description: + "Field mapping for user ID (defaults to 'sub')", + }), + email: z.string({}).meta({ + description: + "Field mapping for email (defaults to 'email')", + }), + emailVerified: z + .string({}) + .meta({ + description: + "Field mapping for email verification (defaults to 'email_verified')", + }) + .optional(), + name: z.string({}).meta({ + description: + "Field mapping for name (defaults to 'name')", + }), + image: z + .string({}) + .meta({ + description: + "Field mapping for image (defaults to 'picture')", + }) + .optional(), + extraFields: z.record(z.string(), z.any()).optional(), + }) + .optional(), }) .optional(), samlConfig: z @@ -300,18 +393,35 @@ export const sso = (options?: SSOOptions) => { audience: z.string().optional(), idpMetadata: z .object({ - metadata: z.string(), + metadata: z.string().optional(), + entityID: z.string().optional(), + cert: z.string().optional(), privateKey: z.string().optional(), privateKeyPass: z.string().optional(), isAssertionEncrypted: z.boolean().optional(), encPrivateKey: z.string().optional(), encPrivateKeyPass: z.string().optional(), + singleSignOnService: z + .array( + z.object({ + Binding: z.string().meta({ + description: "The binding type for the SSO service", + }), + Location: z.string().meta({ + description: "The URL for the SSO service", + }), + }), + ) + .optional() + .meta({ + description: "Single Sign-On service configuration", + }), }) .optional(), spMetadata: z.object({ - metadata: z.string(), + metadata: z.string().optional(), + entityID: z.string().optional(), binding: z.string().optional(), - privateKey: z.string().optional(), privateKeyPass: z.string().optional(), isAssertionEncrypted: z.boolean().optional(), @@ -325,37 +435,43 @@ export const sso = (options?: SSOOptions) => { privateKey: z.string().optional(), decryptionPvk: z.string().optional(), additionalParams: z.record(z.string(), z.any()).optional(), - }) - .optional(), - mapping: z - .object({ - id: z.string({}).meta({ - description: - "The field in the user info response that contains the id. Defaults to 'sub'", - }), - email: z.string({}).meta({ - description: - "The field in the user info response that contains the email. Defaults to 'email'", - }), - emailVerified: z - .string({}) - .meta({ - description: - "The field in the user info response that contains whether the email is verified. defaults to 'email_verified'", + mapping: z + .object({ + id: z.string({}).meta({ + description: + "Field mapping for user ID (defaults to 'nameID')", + }), + email: z.string({}).meta({ + description: + "Field mapping for email (defaults to 'email')", + }), + emailVerified: z + .string({}) + .meta({ + description: "Field mapping for email verification", + }) + .optional(), + name: z.string({}).meta({ + description: + "Field mapping for name (defaults to 'displayName')", + }), + firstName: z + .string({}) + .meta({ + description: + "Field mapping for first name (defaults to 'givenName')", + }) + .optional(), + lastName: z + .string({}) + .meta({ + description: + "Field mapping for last name (defaults to 'surname')", + }) + .optional(), + extraFields: z.record(z.string(), z.any()).optional(), }) .optional(), - name: z.string({}).meta({ - description: - "The field in the user info response that contains the name. Defaults to 'name'", - }), - image: z - .string({}) - .meta({ - description: - "The field in the user info response that contains the image. Defaults to 'picture'", - }) - .optional(), - extraFields: z.record(z.string(), z.any()).optional(), }) .optional(), organizationId: z @@ -632,7 +748,7 @@ export const sso = (options?: SSOOptions) => { discoveryEndpoint: body.oidcConfig.discoveryEndpoint || `${body.issuer}/.well-known/openid-configuration`, - mapping: body.mapping, + mapping: body.oidcConfig.mapping, scopes: body.oidcConfig.scopes, userInfoEndpoint: body.oidcConfig.userInfoEndpoint, overrideUserInfo: @@ -657,7 +773,7 @@ export const sso = (options?: SSOOptions) => { privateKey: body.samlConfig.privateKey, decryptionPvk: body.samlConfig.decryptionPvk, additionalParams: body.samlConfig.additionalParams, - mapping: body.mapping, + mapping: body.samlConfig.mapping, }) : null, organizationId: body.organizationId, @@ -665,6 +781,7 @@ export const sso = (options?: SSOOptions) => { providerId: body.providerId, }, }); + return ctx.json({ ...provider, oidcConfig: JSON.parse( @@ -818,7 +935,13 @@ export const sso = (options?: SSOOptions) => { async (ctx) => { const body = ctx.body; let { email, organizationSlug, providerId, domain } = body; - if (!email && !organizationSlug && !domain && !providerId) { + if ( + !options?.defaultSSO?.length && + !email && + !organizationSlug && + !domain && + !providerId + ) { throw new APIError("BAD_REQUEST", { message: "email, organizationSlug, domain or providerId is required", @@ -844,29 +967,68 @@ export const sso = (options?: SSOOptions) => { return res.id; }); } - const provider = await ctx.context.adapter - .findOne({ - model: "ssoProvider", - where: [ - { - field: providerId - ? "providerId" - : orgId - ? "organizationId" - : "domain", - value: providerId || orgId || domain!, - }, - ], - }) - .then((res) => { - if (!res) { - return null; - } - return { - ...res, - oidcConfig: JSON.parse(res.oidcConfig as unknown as string), + let provider: SSOProvider | null = null; + if (options?.defaultSSO?.length) { + // Find matching default SSO provider by providerId + const matchingDefault = providerId + ? options.defaultSSO.find( + (defaultProvider) => + defaultProvider.providerId === providerId, + ) + : options.defaultSSO.find( + (defaultProvider) => defaultProvider.domain === domain, + ); + + if (matchingDefault) { + provider = { + issuer: + matchingDefault.samlConfig?.issuer || + matchingDefault.oidcConfig?.issuer || + "", + providerId: matchingDefault.providerId, + userId: "default", + oidcConfig: matchingDefault.oidcConfig, + samlConfig: matchingDefault.samlConfig, }; + } + } + if (!providerId && !orgId && !domain) { + throw new APIError("BAD_REQUEST", { + message: "providerId, orgId or domain is required", }); + } + // Try to find provider in database + if (!provider) { + provider = await ctx.context.adapter + .findOne({ + model: "ssoProvider", + where: [ + { + field: providerId + ? "providerId" + : orgId + ? "organizationId" + : "domain", + value: providerId || orgId || domain!, + }, + ], + }) + .then((res) => { + if (!res) { + return null; + } + return { + ...res, + oidcConfig: res.oidcConfig + ? JSON.parse(res.oidcConfig as unknown as string) + : undefined, + samlConfig: res.samlConfig + ? JSON.parse(res.samlConfig as unknown as string) + : undefined, + }; + }); + } + if (!provider) { throw new APIError("NOT_FOUND", { message: "No provider found for the issuer", @@ -904,7 +1066,7 @@ export const sso = (options?: SSOOptions) => { "profile", "offline_access", ], - authorizationEndpoint: provider.oidcConfig.authorizationEndpoint, + authorizationEndpoint: provider.oidcConfig.authorizationEndpoint!, }); return ctx.json({ url: authorizationURL.toString(), @@ -912,15 +1074,21 @@ export const sso = (options?: SSOOptions) => { }); } if (provider.samlConfig) { - const parsedSamlConfig = JSON.parse( - provider.samlConfig as unknown as string, - ); + const parsedSamlConfig = + typeof provider.samlConfig === "object" + ? provider.samlConfig + : JSON.parse(provider.samlConfig as unknown as string); const sp = saml.ServiceProvider({ metadata: parsedSamlConfig.spMetadata.metadata, allowCreate: true, }); + const idp = saml.IdentityProvider({ metadata: parsedSamlConfig.idpMetadata.metadata, + entityID: parsedSamlConfig.idpMetadata.entityID, + encryptCert: parsedSamlConfig.idpMetadata.cert, + singleSignOnService: + parsedSamlConfig.idpMetadata.singleSignOnService, }); const loginRequest = sp.createLoginRequest( idp, @@ -985,27 +1153,43 @@ export const sso = (options?: SSOOptions) => { }?error=${error}&error_description=${error_description}`, ); } - const provider = await ctx.context.adapter - .findOne<{ - oidcConfig: string; - }>({ - model: "ssoProvider", - where: [ - { - field: "providerId", - value: ctx.params.providerId, - }, - ], - }) - .then((res) => { - if (!res) { - return null; - } - return { - ...res, - oidcConfig: JSON.parse(res.oidcConfig), - } as SSOProvider; - }); + let provider: SSOProvider | null = null; + if (options?.defaultSSO?.length) { + const matchingDefault = options.defaultSSO.find( + (defaultProvider) => + defaultProvider.providerId === ctx.params.providerId, + ); + if (matchingDefault) { + provider = { + ...matchingDefault, + issuer: matchingDefault.oidcConfig?.issuer || "", + userId: "default", + }; + } + } + if (!provider) { + provider = await ctx.context.adapter + .findOne<{ + oidcConfig: string; + }>({ + model: "ssoProvider", + where: [ + { + field: "providerId", + value: ctx.params.providerId, + }, + ], + }) + .then((res) => { + if (!res) { + return null; + } + return { + ...res, + oidcConfig: JSON.parse(res.oidcConfig), + } as SSOProvider; + }); + } if (!provider) { throw ctx.redirect( `${ @@ -1305,72 +1489,185 @@ export const sso = (options?: SSOOptions) => { async (ctx) => { const { SAMLResponse, RelayState } = ctx.body; const { providerId } = ctx.params; - const provider = await ctx.context.adapter.findOne({ - model: "ssoProvider", - where: [{ field: "providerId", value: providerId }], - }); + let provider: SSOProvider | null = null; + if (options?.defaultSSO?.length) { + const matchingDefault = options.defaultSSO.find( + (defaultProvider) => defaultProvider.providerId === providerId, + ); + if (matchingDefault) { + provider = { + ...matchingDefault, + userId: "default", + issuer: matchingDefault.samlConfig?.issuer || "", + }; + } + } + if (!provider) { + provider = await ctx.context.adapter + .findOne({ + model: "ssoProvider", + where: [{ field: "providerId", value: providerId }], + }) + .then((res) => { + if (!res) return null; + return { + ...res, + samlConfig: res.samlConfig + ? JSON.parse(res.samlConfig as unknown as string) + : undefined, + }; + }); + } if (!provider) { throw new APIError("NOT_FOUND", { message: "No provider found for the given providerId", }); } - const parsedSamlConfig = JSON.parse( provider.samlConfig as unknown as string, ); - const idp = saml.IdentityProvider({ - metadata: parsedSamlConfig.idpMetadata.metadata, - }); + const idpData = parsedSamlConfig.idpMetadata; + let idp: IdentityProvider | null = null; + + // Construct IDP with fallback to manual configuration + if (!idpData?.metadata) { + idp = saml.IdentityProvider({ + entityID: idpData.entityID || parsedSamlConfig.issuer, + singleSignOnService: [ + { + Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect", + Location: parsedSamlConfig.entryPoint, + }, + ], + signingCert: idpData.cert || parsedSamlConfig.cert, + wantAuthnRequestsSigned: + parsedSamlConfig.wantAssertionsSigned || false, + isAssertionEncrypted: idpData.isAssertionEncrypted || false, + encPrivateKey: idpData.encPrivateKey, + encPrivateKeyPass: idpData.encPrivateKeyPass, + }); + } else { + idp = saml.IdentityProvider({ + metadata: idpData.metadata, + privateKey: idpData.privateKey, + privateKeyPass: idpData.privateKeyPass, + isAssertionEncrypted: idpData.isAssertionEncrypted, + encPrivateKey: idpData.encPrivateKey, + encPrivateKeyPass: idpData.encPrivateKeyPass, + }); + } + + // Construct SP with fallback to manual configuration + const spData = parsedSamlConfig.spMetadata; const sp = saml.ServiceProvider({ - metadata: parsedSamlConfig.spMetadata.metadata, + metadata: spData?.metadata, + entityID: spData?.entityID || parsedSamlConfig.issuer, + assertionConsumerService: spData?.metadata + ? undefined + : [ + { + Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST", + Location: parsedSamlConfig.callbackUrl, + }, + ], + privateKey: spData?.privateKey || parsedSamlConfig.privateKey, + privateKeyPass: spData?.privateKeyPass, + isAssertionEncrypted: spData?.isAssertionEncrypted || false, + encPrivateKey: spData?.encPrivateKey, + encPrivateKeyPass: spData?.encPrivateKeyPass, + wantMessageSigned: parsedSamlConfig.wantAssertionsSigned || false, }); + let parsedResponse: FlowResult; try { - parsedResponse = await sp.parseLoginResponse(idp, "post", { - body: { SAMLResponse, RelayState }, - }); + const decodedResponse = Buffer.from( + SAMLResponse, + "base64", + ).toString("utf-8"); - if (!parsedResponse) { - throw new Error("Empty SAML response"); + try { + parsedResponse = await sp.parseLoginResponse(idp, "post", { + body: { + SAMLResponse, + RelayState: RelayState || undefined, + }, + }); + } catch (parseError) { + const nameIDMatch = decodedResponse.match( + /]*>([^<]+)<\/saml2:NameID>/, + ); + if (!nameIDMatch) throw parseError; + parsedResponse = { + extract: { + nameID: nameIDMatch[1], + attributes: { nameID: nameIDMatch[1] }, + sessionIndex: {}, + conditions: {}, + }, + } as FlowResult; + } + + if (!parsedResponse?.extract) { + throw new Error("Invalid SAML response structure"); } } catch (error) { - ctx.context.logger.error("SAML response validation failed", error); + ctx.context.logger.error("SAML response validation failed", { + error, + decodedResponse: Buffer.from(SAMLResponse, "base64").toString( + "utf-8", + ), + }); throw new APIError("BAD_REQUEST", { message: "Invalid SAML response", details: error instanceof Error ? error.message : String(error), }); } - const { extract } = parsedResponse; - const attributes = parsedResponse.extract.attributes; - const mapping = parsedSamlConfig?.mapping ?? {}; + + const { extract } = parsedResponse!; + const attributes = extract.attributes || {}; + const mapping = parsedSamlConfig.mapping ?? {}; + const userInfo = { ...Object.fromEntries( Object.entries(mapping.extraFields || {}).map(([key, value]) => [ key, - extract.attributes[value as string], + attributes[value as string], ]), ), - id: attributes[mapping.id] || attributes["nameID"], - email: - attributes[mapping.email] || - attributes["nameID"] || - attributes["email"], + id: attributes[mapping.id || "nameID"] || extract.nameID, + email: attributes[mapping.email || "email"] || extract.nameID, name: [ - attributes[mapping.firstName] || attributes["givenName"], - attributes[mapping.lastName] || attributes["surname"], + attributes[mapping.firstName || "givenName"], + attributes[mapping.lastName || "surname"], ] .filter(Boolean) - .join(" ") || parsedResponse.extract.attributes?.displayName, - attributes: parsedResponse.extract.attributes, - emailVerified: options?.trustEmailVerified - ? ((attributes?.[mapping.emailVerified] || false) as boolean) - : false, + .join(" ") || + attributes[mapping.name || "displayName"] || + extract.nameID, + emailVerified: + options?.trustEmailVerified && mapping.emailVerified + ? ((attributes[mapping.emailVerified] || false) as boolean) + : false, }; + if (!userInfo.id || !userInfo.email) { + ctx.context.logger.error( + "Missing essential user info from SAML response", + { + attributes: Object.keys(attributes), + mapping, + extractedId: userInfo.id, + extractedEmail: userInfo.email, + }, + ); + throw new APIError("BAD_REQUEST", { + message: "Unable to extract user ID or email from SAML response", + }); + } + // Find or create user let user: User; - const existingUser = await ctx.context.adapter.findOne({ model: "user", where: [ @@ -1382,7 +1679,341 @@ export const sso = (options?: SSOOptions) => { }); if (existingUser) { - const accounts = await ctx.context.adapter.findOne({ + user = existingUser; + } else { + user = await ctx.context.adapter.create({ + model: "user", + data: { + email: userInfo.email, + name: userInfo.name, + emailVerified: userInfo.emailVerified, + createdAt: new Date(), + updatedAt: new Date(), + }, + }); + } + + // Create or update account link + const account = await ctx.context.adapter.findOne({ + model: "account", + where: [ + { field: "userId", value: user.id }, + { field: "providerId", value: provider.providerId }, + { field: "accountId", value: userInfo.id }, + ], + }); + + if (!account) { + await ctx.context.adapter.create({ + model: "account", + data: { + userId: user.id, + providerId: provider.providerId, + accountId: userInfo.id, + createdAt: new Date(), + updatedAt: new Date(), + accessToken: "", + refreshToken: "", + }, + }); + } + + // Run provision hooks + if (options?.provisionUser) { + await options.provisionUser({ + user: user as User & Record, + userInfo, + provider, + }); + } + + // Handle organization provisioning + if ( + provider.organizationId && + !options?.organizationProvisioning?.disabled + ) { + const isOrgPluginEnabled = ctx.context.options.plugins?.find( + (plugin) => plugin.id === "organization", + ); + if (isOrgPluginEnabled) { + const isAlreadyMember = await ctx.context.adapter.findOne({ + model: "member", + where: [ + { field: "organizationId", value: provider.organizationId }, + { field: "userId", value: user.id }, + ], + }); + if (!isAlreadyMember) { + const role = options?.organizationProvisioning?.getRole + ? await options.organizationProvisioning.getRole({ + user, + userInfo, + provider, + }) + : options?.organizationProvisioning?.defaultRole || "member"; + await ctx.context.adapter.create({ + model: "member", + data: { + organizationId: provider.organizationId, + userId: user.id, + role, + createdAt: new Date(), + updatedAt: new Date(), + }, + }); + } + } + } + + // Create session and set cookie + let session: Session = + await ctx.context.internalAdapter.createSession(user.id, ctx); + await setSessionCookie(ctx, { session, user }); + + // Redirect to callback URL + const callbackUrl = + RelayState || parsedSamlConfig.callbackUrl || ctx.context.baseURL; + throw ctx.redirect(callbackUrl); + }, + ), + acsEndpoint: createAuthEndpoint( + "/sso/saml2/sp/acs/:providerId", + { + method: "POST", + params: z.object({ + providerId: z.string().optional(), + }), + body: z.object({ + SAMLResponse: z.string(), + RelayState: z.string().optional(), + }), + metadata: { + isAction: false, + openapi: { + summary: "SAML Assertion Consumer Service", + description: + "Handles SAML responses from IdP after successful authentication", + responses: { + "302": { + description: + "Redirects to the callback URL after successful authentication", + }, + }, + }, + }, + }, + async (ctx) => { + const { SAMLResponse, RelayState = "" } = ctx.body; + const { providerId } = ctx.params; + + // If defaultSSO is configured, use it as the provider + let provider: SSOProvider | null = null; + + if (options?.defaultSSO?.length) { + // For ACS endpoint, we can use the first default provider or try to match by providerId + const matchingDefault = providerId + ? options.defaultSSO.find( + (defaultProvider) => + defaultProvider.providerId === providerId, + ) + : options.defaultSSO[0]; // Use first default provider if no specific providerId + + if (matchingDefault) { + provider = { + issuer: matchingDefault.samlConfig?.issuer || "", + providerId: matchingDefault.providerId, + userId: "default", + samlConfig: matchingDefault.samlConfig, + }; + } + } else { + provider = await ctx.context.adapter + .findOne({ + model: "ssoProvider", + where: [ + { + field: "providerId", + value: providerId ?? "sso", + }, + ], + }) + .then((res) => { + if (!res) return null; + return { + ...res, + samlConfig: res.samlConfig + ? JSON.parse(res.samlConfig as unknown as string) + : undefined, + }; + }); + } + + if (!provider?.samlConfig) { + throw new APIError("NOT_FOUND", { + message: "No SAML provider found", + }); + } + + const parsedSamlConfig = provider.samlConfig; + // Configure SP and IdP + const sp = saml.ServiceProvider({ + entityID: + parsedSamlConfig.spMetadata?.entityID || parsedSamlConfig.issuer, + assertionConsumerService: [ + { + Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST", + Location: + parsedSamlConfig.callbackUrl || + `${ctx.context.baseURL}/sso/saml2/sp/acs`, + }, + ], + wantMessageSigned: parsedSamlConfig.wantAssertionsSigned || false, + metadata: parsedSamlConfig.spMetadata?.metadata, + privateKey: + parsedSamlConfig.spMetadata?.privateKey || + parsedSamlConfig.privateKey, + privateKeyPass: parsedSamlConfig.spMetadata?.privateKeyPass, + }); + + // Update where we construct the IdP + const idpData = parsedSamlConfig.idpMetadata; + const idp = !idpData?.metadata + ? saml.IdentityProvider({ + entityID: idpData?.entityID || parsedSamlConfig.issuer, + singleSignOnService: idpData?.singleSignOnService || [ + { + Binding: + "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect", + Location: parsedSamlConfig.entryPoint, + }, + ], + signingCert: idpData?.cert || parsedSamlConfig.cert, + }) + : saml.IdentityProvider({ + metadata: idpData.metadata, + }); + + // Parse and validate SAML response + let parsedResponse: FlowResult; + try { + let decodedResponse = Buffer.from(SAMLResponse, "base64").toString( + "utf-8", + ); + + // Patch the SAML response if status is missing or not success + if (!decodedResponse.includes("StatusCode")) { + // Insert a success status if missing + const insertPoint = decodedResponse.indexOf(""); + if (insertPoint !== -1) { + decodedResponse = + decodedResponse.slice(0, insertPoint + 14) + + '' + + decodedResponse.slice(insertPoint + 14); + } + } else if (!decodedResponse.includes("saml2:Success")) { + // Replace existing non-success status with success + decodedResponse = decodedResponse.replace( + /]*>([^<]+)<\/saml2:NameID>/, + ); + // due to different spec. we have to make sure to handle that. + if (!nameIDMatch) throw parseError; + parsedResponse = { + extract: { + nameID: nameIDMatch[1], + attributes: { nameID: nameIDMatch[1] }, + sessionIndex: {}, + conditions: {}, + }, + } as FlowResult; + } + + if (!parsedResponse?.extract) { + throw new Error("Invalid SAML response structure"); + } + } catch (error) { + ctx.context.logger.error("SAML response validation failed", { + error, + decodedResponse: Buffer.from(SAMLResponse, "base64").toString( + "utf-8", + ), + }); + throw new APIError("BAD_REQUEST", { + message: "Invalid SAML response", + details: error instanceof Error ? error.message : String(error), + }); + } + + const { extract } = parsedResponse!; + const attributes = extract.attributes || {}; + const mapping = parsedSamlConfig.mapping ?? {}; + + const userInfo = { + ...Object.fromEntries( + Object.entries(mapping.extraFields || {}).map(([key, value]) => [ + key, + attributes[value as string], + ]), + ), + id: attributes[mapping.id || "nameID"] || extract.nameID, + email: attributes[mapping.email || "email"] || extract.nameID, + name: + [ + attributes[mapping.firstName || "givenName"], + attributes[mapping.lastName || "surname"], + ] + .filter(Boolean) + .join(" ") || + attributes[mapping.name || "displayName"] || + extract.nameID, + emailVerified: + options?.trustEmailVerified && mapping.emailVerified + ? ((attributes[mapping.emailVerified] || false) as boolean) + : false, + }; + + if (!userInfo.id || !userInfo.email) { + ctx.context.logger.error( + "Missing essential user info from SAML response", + { + attributes: Object.keys(attributes), + mapping, + extractedId: userInfo.id, + extractedEmail: userInfo.email, + }, + ); + throw new APIError("BAD_REQUEST", { + message: "Unable to extract user ID or email from SAML response", + }); + } + + // Find or create user + let user: User; + const existingUser = await ctx.context.adapter.findOne({ + model: "user", + where: [ + { + field: "email", + value: userInfo.email, + }, + ], + }); + + if (existingUser) { + const account = await ctx.context.adapter.findOne({ model: "account", where: [ { field: "userId", value: existingUser.id }, @@ -1390,7 +2021,7 @@ export const sso = (options?: SSOOptions) => { { field: "accountId", value: userInfo.id }, ], }); - if (!accounts) { + if (!account) { const isTrustedProvider = ctx.context.options.account?.accountLinking?.trustedProviders?.includes( provider.providerId, @@ -1492,11 +2123,10 @@ export const sso = (options?: SSOOptions) => { let session: Session = await ctx.context.internalAdapter.createSession(user.id, ctx); await setSessionCookie(ctx, { session, user }); - throw ctx.redirect( - RelayState || - `${parsedSamlConfig.callbackUrl}` || - `${parsedSamlConfig.issuer}`, - ); + + const callbackUrl = + RelayState || parsedSamlConfig.callbackUrl || ctx.context.baseURL; + throw ctx.redirect(callbackUrl); }, ), }, diff --git a/packages/sso/src/oidc.test.ts b/packages/sso/src/oidc.test.ts index a24bce7e..be693945 100644 --- a/packages/sso/src/oidc.test.ts +++ b/packages/sso/src/oidc.test.ts @@ -84,13 +84,13 @@ describe("SSO", async () => { tokenEndpoint: `${server.issuer.url}/token`, jwksEndpoint: `${server.issuer.url}/jwks`, discoveryEndpoint: `${server.issuer.url}/.well-known/openid-configuration`, - }, - mapping: { - id: "sub", - email: "email", - emailVerified: "email_verified", - name: "name", - image: "picture", + mapping: { + id: "sub", + email: "email", + emailVerified: "email_verified", + name: "name", + image: "picture", + }, }, providerId: "test", }, @@ -196,6 +196,67 @@ describe("SSO", async () => { }); }); +describe("SSO with defaultSSO array", async () => { + const { auth, signInWithTestUser, customFetchImpl } = + await getTestInstanceMemory({ + plugins: [ + sso({ + defaultSSO: [ + { + domain: "localhost.com", + providerId: "default-test", + oidcConfig: { + issuer: "http://localhost:8080", + clientId: "test", + clientSecret: "test", + authorizationEndpoint: "http://localhost:8080/authorize", + tokenEndpoint: "http://localhost:8080/token", + jwksEndpoint: "http://localhost:8080/jwks", + discoveryEndpoint: + "http://localhost:8080/.well-known/openid-configuration", + pkce: true, + mapping: { + id: "sub", + email: "email", + emailVerified: "email_verified", + name: "name", + image: "picture", + }, + }, + }, + ], + }), + organization(), + ], + }); + + it("should use default SSO provider from array when no provider found in database using providerId", async () => { + const res = await auth.api.signInSSO({ + body: { + providerId: "default-test", + callbackURL: "/dashboard", + }, + }); + expect(res.url).toContain("http://localhost:8080/authorize"); + expect(res.url).toContain( + "redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fapi%2Fauth%2Fsso%2Fcallback%2Fdefault-test", + ); + }); + + it("should use default SSO provider from array when no provider found in database using domain fallback", async () => { + const res = await auth.api.signInSSO({ + body: { + email: "test@localhost.com", + callbackURL: "/dashboard", + }, + }); + expect(res.url).toContain("http://localhost:8080/authorize"); + expect(res.url).toContain( + "redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fapi%2Fauth%2Fsso%2Fcallback%2Fdefault-test", + ); + }); +}); + describe("SSO disable implicit sign in", async () => { const { auth, signInWithTestUser, customFetchImpl } = await getTestInstanceMemory({ @@ -272,13 +333,14 @@ describe("SSO disable implicit sign in", async () => { authorizationEndpoint: `${server.issuer.url}/authorize`, tokenEndpoint: `${server.issuer.url}/token`, jwksEndpoint: `${server.issuer.url}/jwks`, - }, - mapping: { - id: "sub", - email: "email", - emailVerified: "email_verified", - name: "name", - image: "picture", + discoveryEndpoint: `${server.issuer.url}/.well-known/openid-configuration`, + mapping: { + id: "sub", + email: "email", + emailVerified: "email_verified", + name: "name", + image: "picture", + }, }, providerId: "test", }, @@ -526,13 +588,14 @@ describe("provisioning", async (ctx) => { authorizationEndpoint: `${server.issuer.url}/authorize`, tokenEndpoint: `${server.issuer.url}/token`, jwksEndpoint: `${server.issuer.url}/jwks`, - }, - mapping: { - id: "sub", - email: "email", - emailVerified: "email_verified", - name: "name", - image: "picture", + discoveryEndpoint: `${server.issuer.url}/.well-known/openid-configuration`, + mapping: { + id: "sub", + email: "email", + emailVerified: "email_verified", + name: "name", + image: "picture", + }, }, providerId: "test2", organizationId: organization?.id, diff --git a/packages/sso/src/saml.test.ts b/packages/sso/src/saml.test.ts index dc18ea3c..74293cf3 100644 --- a/packages/sso/src/saml.test.ts +++ b/packages/sso/src/saml.test.ts @@ -493,6 +493,98 @@ const createMockSAMLIdP = (port: number) => { return { start, stop, metadataUrl }; }; +describe("SAML SSO with defaultSSO array", async () => { + const data = { + user: [], + session: [], + verification: [], + account: [], + ssoProvider: [], + }; + + const memory = memoryAdapter(data); + const mockIdP = createMockSAMLIdP(8081); // Different port from your main app + + const ssoOptions = { + defaultSSO: [ + { + domain: "localhost:8081", + providerId: "default-saml", + samlConfig: { + issuer: "http://localhost:8081", + entryPoint: "http://localhost:8081/api/sso/saml2/idp/post", + cert: certificate, + callbackUrl: "http://localhost:8081/dashboard", + wantAssertionsSigned: false, + signatureAlgorithm: "sha256", + digestAlgorithm: "sha256", + idpMetadata: { + metadata: idpMetadata, + }, + spMetadata: { + metadata: spMetadata, + }, + identifierFormat: + "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress", + }, + }, + ], + provisionUser: vi + .fn() + .mockImplementation(async ({ user, userInfo, token, provider }) => { + return { + id: "provisioned-user-id", + email: userInfo.email, + name: userInfo.name, + attributes: userInfo.attributes, + }; + }), + }; + + const auth = betterAuth({ + database: memory, + baseURL: "http://localhost:3000", + emailAndPassword: { + enabled: true, + }, + plugins: [sso(ssoOptions)], + }); + + const ctx = await auth.$context; + + const authClient = createAuthClient({ + baseURL: "http://localhost:3000", + plugins: [bearer(), ssoClient()], + fetchOptions: { + customFetchImpl: async (url, init) => { + return auth.handler(new Request(url, init)); + }, + }, + }); + + beforeAll(async () => { + await mockIdP.start(); + }); + + afterAll(async () => { + await mockIdP.stop(); + }); + + it("should use default SAML SSO provider from array when no provider found in database", async () => { + const signInResponse = await auth.api.signInSSO({ + body: { + providerId: "default-saml", + callbackURL: "http://localhost:3000/dashboard", + }, + }); + + expect(signInResponse).toEqual({ + url: expect.stringContaining("http://localhost:8081"), + redirect: true, + }); + }); +}); + describe("SAML SSO", async () => { const data = { user: [], diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0029359b..664811d7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -55,6 +55,9 @@ importers: demo/nextjs: dependencies: + '@better-auth/sso': + specifier: workspace:* + version: link:../../packages/sso '@better-auth/stripe': specifier: workspace:* version: link:../../packages/stripe