Beautiful Open-Source Form Builder
Fix self-hosted OIDC configuration and recovery (#1201)
Julien Nahume41d1e13a7e2
diff --git a/api/app/Enterprise/Oidc/Requests/StoreOidcConnectionRequest.php b/api/app/Enterprise/Oidc/Requests/StoreOidcConnectionRequest.phpindex 43721e2e6..0268b141a 100644--- a/api/app/Enterprise/Oidc/Requests/StoreOidcConnectionRequest.php+++ b/api/app/Enterprise/Oidc/Requests/StoreOidcConnectionRequest.php@@ -57,7 +57,7 @@ class StoreOidcConnectionRequest extends FormRequest'options.group_role_mappings' => ['nullable', 'array'],'options.group_role_mappings.*.idp_group' => ['required_with:options.group_role_mappings', 'string', 'max:255'],'options.group_role_mappings.*.role' => ['required_with:options.group_role_mappings', 'string', Rule::in(['owner', 'admin', 'editor', 'member'])],- 'redirect_path' => ['nullable', 'string', 'max:255'],+ 'redirect_path' => ['nullable', 'url', 'max:255'],'enabled' => ['boolean'],];}diff --git a/api/app/Enterprise/Oidc/Requests/UpdateOidcConnectionRequest.php b/api/app/Enterprise/Oidc/Requests/UpdateOidcConnectionRequest.phpindex 78766d41b..67a75906e 100644--- a/api/app/Enterprise/Oidc/Requests/UpdateOidcConnectionRequest.php+++ b/api/app/Enterprise/Oidc/Requests/UpdateOidcConnectionRequest.php@@ -61,7 +61,7 @@ class UpdateOidcConnectionRequest extends FormRequest'options.group_role_mappings' => ['nullable', 'array'],'options.group_role_mappings.*.idp_group' => ['required_with:options.group_role_mappings', 'string', 'max:255'],'options.group_role_mappings.*.role' => ['required_with:options.group_role_mappings', 'string', Rule::in(['owner', 'admin', 'editor', 'member'])],- 'redirect_path' => ['nullable', 'string', 'max:255'],+ 'redirect_path' => ['nullable', 'url', 'max:255'],'enabled' => ['sometimes', 'boolean'],];}diff --git a/api/tests/Feature/Enterprise/Oidc/OidcConnectionControllerTest.php b/api/tests/Feature/Enterprise/Oidc/OidcConnectionControllerTest.phpindex 506dff891..e4c538c0f 100644--- a/api/tests/Feature/Enterprise/Oidc/OidcConnectionControllerTest.php+++ b/api/tests/Feature/Enterprise/Oidc/OidcConnectionControllerTest.php@@ -508,11 +508,15 @@ describe('OidcConnectionController - Update Connection', function () {$response = $this->patchJson("/open/workspaces/{$workspace->id}/oidc-connections/{$connection->id}",- ['name' => 'Updated Name']+ [+ 'name' => 'Updated Name',+ 'redirect_path' => 'https://forms.example.com/auth/company-sso/callback',+ ]);$response->assertSuccessful();expect($connection->fresh()->client_secret)->toBe('old-secret');+ expect($connection->fresh()->redirect_path)->toBe('https://forms.example.com/auth/company-sso/callback');});it('merges options instead of replacing', function () {diff --git a/client/api/oidc.js b/client/api/oidc.jsindex cd11a2d5e..a21ab6181 100644--- a/client/api/oidc.js+++ b/client/api/oidc.js@@ -19,6 +19,9 @@ export const oidcApi = {// Email-based OIDC lookup (for login flow)getOptionsForEmail: (email) => apiService.post('/auth/oidc/options', { email }),++ // Starts a fresh OIDC authorization request for a known connection.+ redirect: (slug) => apiService.post(`/auth/${slug}/redirect`),// OIDC callback - processes authorization code and returns token/usercallback: (slug, queryParams, stateVerifier = null) => {diff --git a/client/components/pages/auth/components/LoginForm.vue b/client/components/pages/auth/components/LoginForm.vueindex 0933ca664..d938e7564 100644--- a/client/components/pages/auth/components/LoginForm.vue+++ b/client/components/pages/auth/components/LoginForm.vue@@ -117,7 +117,7 @@import ForgotPasswordModal from "../ForgotPasswordModal.vue"import GoogleOneTap from "~/components/vendor/GoogleOneTap.vue"import { WindowMessageTypes } from "~/composables/useWindowMessage"-import { storeOidcStateVerifier } from "~/lib/oidc/state-verifier"+import { clearOidcAutomaticRetry, storeOidcStateVerifier } from "~/lib/oidc/state-verifier"// Propsconst props = defineProps({@@ -189,6 +189,7 @@ const checkOidcOptions = async () => {if (response.action === 'redirect') {// Get the redirect URL from the backendtry {+ clearOidcAutomaticRetry(response.slug)const redirectResponse = await form.post(`/auth/${response.slug}/redirect`)if (redirectResponse.redirect_url) {diff --git a/client/components/workspaces/settings/sso/Oidc.vue b/client/components/workspaces/settings/sso/Oidc.vueindex 5a5c33b8f..37d69b9c2 100644--- a/client/components/workspaces/settings/sso/Oidc.vue+++ b/client/components/workspaces/settings/sso/Oidc.vue@@ -22,7 +22,7 @@v-if="canManageConnections && canAccessFeature"label="Add Connection"icon="i-heroicons-plus"- @click="showCreateModal = true"+ @click="openCreateModal"/><UButtonv-else-if="canManageConnections && !canAccessFeature"@@ -67,7 +67,7 @@v-if="canManageConnections && canAccessFeature"label="Add Your First Connection"icon="i-heroicons-plus"- @click="showCreateModal = true"+ @click="openCreateModal"/><UButtonv-else-if="canManageConnections && !canAccessFeature"@@ -172,15 +172,17 @@ const openSsoLicenseModal = (error) => {const showCreateModal = ref(false)const editingConnection = ref(null)-const connectionForm = useForm({+const emptyConnectionData = () => ({name: '',slug: '',issuer: '',client_id: '',client_secret: '',domain: '',+ redirect_path: '',enabled: true,options: {+ require_state: true,field_mappings: {email: '',name: ''@@ -189,18 +191,33 @@ const connectionForm = useForm({}})+const connectionForm = useForm(emptyConnectionData())+// Create mutations following useWorkspaces.js patternconst createMutation = create()const deleteMutation = remove()+const openCreateModal = () => {+ editingConnection.value = null+ connectionForm.resetAndFill(emptyConnectionData())+ showCreateModal.value = true+}+const saveConnection = () => {if (editingConnection.value) {// Update existing connectionconst updateMutation = update(editingConnection.value.id)+ const keepExistingSecret = !connectionForm.client_secret?.trim()++ // The API intentionally preserves the existing secret when it is omitted.+ // Do not send the empty field shown in the edit form as a replacement.+ if (keepExistingSecret) {+ delete connectionForm.client_secret+ }+connectionForm.mutate(updateMutation).then(() => {alert.success('OIDC connection updated successfully')- showCreateModal.value = falsecancelEdit()}).catch((error) => {@@ -210,13 +227,17 @@ const saveConnection = () => {alert.error(error.response?._data?.message ?? 'Failed to update connection')}})+ .finally(() => {+ if (keepExistingSecret) {+ connectionForm.client_secret = ''+ }+ })} else {// Create new connectionconnectionForm.mutate(createMutation).then(() => {alert.success('OIDC connection created successfully')- showCreateModal.value = false- connectionForm.reset()+ cancelEdit()}).catch((error) => {// Form handles validation errors automatically@@ -238,7 +259,9 @@ const editConnection = (connection) => {client_secret: '', // Don't pre-fill secretenabled: connection.enabled,domain: connection.domain ?? '',+ redirect_path: connection.redirect_url ?? '',options: {+ require_state: connection.options?.require_state ?? true,field_mappings: {email: connection.options?.field_mappings?.email ?? '',name: connection.options?.field_mappings?.name ?? ''@@ -267,7 +290,7 @@ const deleteConnection = (connection) => {const cancelEdit = () => {editingConnection.value = null- connectionForm.reset()+ connectionForm.resetAndFill(emptyConnectionData())showCreateModal.value = false}</script>diff --git a/client/components/workspaces/settings/sso/OidcConnectionModal.vue b/client/components/workspaces/settings/sso/OidcConnectionModal.vueindex bd298e6d5..f5010cb3f 100644--- a/client/components/workspaces/settings/sso/OidcConnectionModal.vue+++ b/client/components/workspaces/settings/sso/OidcConnectionModal.vue@@ -70,6 +70,19 @@:content="redirectUri"label="Copy"/>+ <div v-if="isEditing" class="mt-3 border-t border-blue-200 pt-3">+ <p class="mb-2 text-xs text-blue-700">+ If your instance URL changed, refresh this callback URL, update it in your provider, then save this connection.+ </p>+ <UButton+ type="button"+ size="xs"+ color="primary"+ variant="soft"+ label="Use current app URL"+ @click="useCurrentAppUrl"+ />+ </div></div><TextInput@@ -78,7 +91,7 @@label="Issuer URL":required="true"placeholder="https://idp.example.com"- help="Issued by your OIDC provider. Must match the redirect registered in that provider."+ help="The issuer published by your OIDC provider, usually available in its OpenID configuration."/><TextInput@@ -92,10 +105,11 @@<TextInputname="client_secret":form="form"- label="Client Secret"- :required="true"- type="password"+ :label="isEditing ? 'Client Secret (optional)' : 'Client Secret'"+ :required="!isEditing"+ native-type="password"placeholder="your-client-secret"+ :help="isEditing ? 'Leave blank to keep the existing client secret.' : undefined"/><ToggleSwitchInput@@ -166,8 +180,9 @@<TextInput:name="`options.group_role_mappings.${index}.idp_group`":form="form"- label="IdP Group"- placeholder="opnform_admins"+ label="Token group value"+ placeholder="group-id-or-name"+ help="Exact, case-sensitive value from the ID token's groups or group claim.":required="true"size="sm"/>@@ -292,6 +307,10 @@ const showFieldMappings = ref(hasFieldMappings.value)const showRoleMapping = ref(roleMappings.value.length > 0)const redirectUri = computed(() => {+ if (props.form.redirect_path) {+ return props.form.redirect_path+ }+const slug = props.form.slugif (!slug) return null@@ -299,6 +318,11 @@ const redirectUri = computed(() => {return appUrl(`/auth/${slug}/callback`)})+const useCurrentAppUrl = () => {+ if (!props.form.slug) return+ props.form.redirect_path = appUrl(`/auth/${props.form.slug}/callback`)+}+watch(hasFieldMappings, (newVal) => {if (!showFieldMappings.value && newVal) {showFieldMappings.value = true@@ -330,4 +354,3 @@ const handleCancel = () => {emit('update:modelValue', false)}</script>-diff --git a/client/lib/oidc/redirect.js b/client/lib/oidc/redirect.jsnew file mode 100644index 000000000..489570954--- /dev/null+++ b/client/lib/oidc/redirect.js@@ -0,0 +1,3 @@+export const redirectToOidcProvider = (url) => {+ window.location.replace(url)+}diff --git a/client/lib/oidc/state-verifier.js b/client/lib/oidc/state-verifier.jsindex 6f3d34efb..c088dfb81 100644--- a/client/lib/oidc/state-verifier.js+++ b/client/lib/oidc/state-verifier.js@@ -1,4 +1,5 @@const stateVerifierStorageKey = (slug, state) => `oidc_state_verifier:${slug}:${state}`+const automaticRetryStorageKey = (slug) => `oidc_automatic_retry:${slug}`export const storeOidcStateVerifier = (slug, state, verifier) => {if (import.meta.server || !slug || !state || !verifier) {@@ -30,3 +31,39 @@ export const consumeOidcStateVerifier = (slug, state) => {return null}}++export const canAutomaticallyRetryOidcSignIn = (slug) => {+ if (import.meta.server || !slug) {+ return false+ }++ try {+ return !sessionStorage.getItem(automaticRetryStorageKey(slug))+ } catch {+ return false+ }+}++export const markOidcAutomaticRetry = (slug) => {+ if (import.meta.server || !slug) {+ return+ }++ try {+ sessionStorage.setItem(automaticRetryStorageKey(slug), '1')+ } catch {+ // Ignore storage failures and fall back to the manual recovery screen.+ }+}++export const clearOidcAutomaticRetry = (slug) => {+ if (import.meta.server || !slug) {+ return+ }++ try {+ sessionStorage.removeItem(automaticRetryStorageKey(slug))+ } catch {+ // Ignore storage failures. A fresh manual login can still continue normally.+ }+}diff --git a/client/pages/auth/[slug]/callback.vue b/client/pages/auth/[slug]/callback.vueindex c08c67f5e..704837f45 100644--- a/client/pages/auth/[slug]/callback.vue+++ b/client/pages/auth/[slug]/callback.vue@@ -14,7 +14,7 @@class="m-10"><h3 class="my-6 text-center">- {{ showTwoFactorModal ? 'Verifying your code...' : 'Completing sign in...' }}+ {{ showTwoFactorModal ? 'Verifying your code...' : isRetrying ? 'Reconnecting securely...' : 'Completing sign in...' }}</h3><Loader class="h-6 w-6 mx-auto m-10" /></div>@@ -27,6 +27,7 @@color="error"variant="subtle"class="w-full"+ title="Sign-in could not be completed":description="error"/><UButton@@ -37,7 +38,7 @@/><UButton:to="{ name: 'login' }"- label="Back to login"+ label="Back to sign in"/></div></div>@@ -46,18 +47,51 @@<script setup>import { oidcApi } from "~/api"-import { consumeOidcStateVerifier } from "~/lib/oidc/state-verifier"+import { redirectToOidcProvider } from "~/lib/oidc/redirect"+import {+ canAutomaticallyRetryOidcSignIn,+ clearOidcAutomaticRetry,+ consumeOidcStateVerifier,+ markOidcAutomaticRetry,+ storeOidcStateVerifier,+} from "~/lib/oidc/state-verifier"const router = useRouter()const route = useRoute()const loading = ref(true)const error = ref(null)const linkToken = ref(null)+const callbackStarted = ref(false)+const isRetrying = ref(false)const { startLink } = useOidcLinking()const authFlow = useAuthFlow()const { showTwoFactorModal, pendingAuthToken, handleTwoFactorVerified, handleTwoFactorCancel: handleTwoFactorCancelFromFlow, handleTwoFactorError } = authFlow+const authorizationCodeWasAlreadyUsed = (providerError) => {+ return providerError.includes('AADSTS54005') || providerError.includes('Authorization code was already redeemed')+}++const retryOidcSignIn = (slug) => {+ markOidcAutomaticRetry(slug)+ isRetrying.value = true++ return oidcApi.redirect(slug)+ .then((response) => {+ if (!response.redirect_url) {+ return false+ }++ storeOidcStateVerifier(slug, response.state, response.state_verifier)+ redirectToOidcProvider(response.redirect_url)+ return true+ })+ .catch(() => false)+}+const handleCallback = async () => {+ if (callbackStarted.value) return++ callbackStarted.value = trueconst slug = route.params.slugtry {@@ -88,6 +122,7 @@ const handleCallback = async () => {// Handle authentication success (handles both 2FA and non-2FA cases)// handleAuthSuccess will check for requires_2fa and show modal if neededawait authFlow.handleAuthSuccess(response, 'oidc', response.new_user)+ clearOidcAutomaticRetry(slug)// If 2FA modal is shown, don't redirect yet (handled in handleTwoFactorVerifiedAndRedirect)if (showTwoFactorModal.value) {@@ -115,12 +150,28 @@ const handleCallback = async () => {const errorResponse = err.response?._data || {}const errorMessage = errorResponse.message || err.message || "Authentication failed"- error.value = errorMessage+ const providerError = [errorResponse.message, errorResponse.error_description, err.message]+ .filter(Boolean)+ .join(' ')+ error.value = 'We could not complete this sign-in. Return to sign in, or contact your administrator if the problem continues.'// Handle specific error casesif (errorResponse.error === 'oidc_account_link_required' && errorResponse.link_token) {error.value = 'An account with this email already exists. Please link your existing account to continue.'linkToken.value = errorResponse.link_token+ } else if (authorizationCodeWasAlreadyUsed(providerError)) {+ if (canAutomaticallyRetryOidcSignIn(slug)) {+ return retryOidcSignIn(slug)+ .then((retryStarted) => {+ if (retryStarted) return++ isRetrying.value = false+ error.value = 'We could not reconnect automatically. Return to sign in to try again, or contact your administrator if the problem continues.'+ loading.value = false+ })+ }++ error.value = 'We could not reconnect automatically. Return to sign in to try again, or contact your administrator if the problem continues.'} else if (errorMessage.includes('more than 2 users')) {error.value = 'This self-hosted instance is limited to 2 users without an Enterprise license. Ask the instance admin to activate a license or remove another user.'} else if (errorMessage.includes('account with this email already exists')) {diff --git a/client/test/nuxt/oidc-link-flow.spec.ts b/client/test/nuxt/oidc-link-flow.spec.tsindex 7af7d3a2d..b31453949 100644--- a/client/test/nuxt/oidc-link-flow.spec.ts+++ b/client/test/nuxt/oidc-link-flow.spec.ts@@ -4,9 +4,24 @@ import { ref } from 'vue'import OidcCallbackPage from '~/pages/auth/[slug]/callback.vue'import LoginForm from '~/components/pages/auth/components/LoginForm.vue'-const { startLinkSpy, completeLinkIfNeededSpy } = vi.hoisted(() => ({+const {+ startLinkSpy,+ completeLinkIfNeededSpy,+ redirectToOidcProviderSpy,+ canAutomaticallyRetryOidcSignInSpy,+ clearOidcAutomaticRetrySpy,+ consumeOidcStateVerifierSpy,+ markOidcAutomaticRetrySpy,+ storeOidcStateVerifierSpy,+} = vi.hoisted(() => ({startLinkSpy: vi.fn(),completeLinkIfNeededSpy: vi.fn(() => Promise.resolve(true)),+ redirectToOidcProviderSpy: vi.fn(),+ canAutomaticallyRetryOidcSignInSpy: vi.fn(() => true),+ clearOidcAutomaticRetrySpy: vi.fn(),+ consumeOidcStateVerifierSpy: vi.fn(() => null),+ markOidcAutomaticRetrySpy: vi.fn(),+ storeOidcStateVerifierSpy: vi.fn(),}))vi.mock('~/middleware/01.check-auth.global', () => ({@@ -58,10 +73,23 @@ vi.mock('~/composables/useOidcLinking', () => ({vi.mock('~/api', () => ({oidcApi: {callback: vi.fn(),+ redirect: vi.fn(),link: vi.fn(),},}))+vi.mock('~/lib/oidc/redirect', () => ({+ redirectToOidcProvider: redirectToOidcProviderSpy,+}))++vi.mock('~/lib/oidc/state-verifier', () => ({+ canAutomaticallyRetryOidcSignIn: canAutomaticallyRetryOidcSignInSpy,+ clearOidcAutomaticRetry: clearOidcAutomaticRetrySpy,+ consumeOidcStateVerifier: consumeOidcStateVerifierSpy,+ markOidcAutomaticRetry: markOidcAutomaticRetrySpy,+ storeOidcStateVerifier: storeOidcStateVerifierSpy,+}))+describe('OIDC link flow', () => {const setupGlobals = (routeOverrides = {}) => {const router = {@@ -125,9 +153,11 @@ describe('OIDC link flow', () => {beforeEach(() => {vi.clearAllMocks()+ canAutomaticallyRetryOidcSignInSpy.mockReturnValue(true)})afterEach(() => {+ sessionStorage.clear()vi.unstubAllGlobals()})@@ -173,6 +203,90 @@ describe('OIDC link flow', () => {vi.useRealTimers()})+ it('automatically starts one fresh sign-in when an authorization code was already used', async () => {+ vi.useFakeTimers()+ const apiModule = await import('~/api') as { oidcApi: any }+ const oidcApi = apiModule.oidcApi+ setupGlobals()++ oidcApi.callback.mockRejectedValue({+ message: 'AADSTS54005: Authorization code was already redeemed',+ })+ oidcApi.redirect.mockResolvedValue({+ redirect_url: 'https://idp.example.com/authorize',+ state: 'fresh-state',+ state_verifier: 'fresh-verifier',+ })++ const wrapper = mount(OidcCallbackPage, {+ global: {+ stubs: {+ TwoFactorVerificationModal: true,+ Loader: true,+ UAlert: {+ template: '<div class="alert">{{ title }} {{ description }}</div>',+ props: ['title', 'description'],+ },+ UButton: {+ template: '<button>{{ label }}<slot /></button>',+ props: ['label', 'color', 'variant', 'to'],+ emits: ['click'],+ },+ },+ },+ })++ await flushPromises()+ vi.runAllTimers()+ await flushPromises()++ expect(wrapper.text()).toContain('Reconnecting securely...')+ expect(oidcApi.redirect).toHaveBeenCalledOnce()+ expect(markOidcAutomaticRetrySpy).toHaveBeenCalledOnce()+ expect(storeOidcStateVerifierSpy).toHaveBeenCalledOnce()+ expect(redirectToOidcProviderSpy).toHaveBeenCalledWith('https://idp.example.com/authorize')+ vi.useRealTimers()+ })++ it('shows a recovery action instead of retrying a second time', async () => {+ vi.useFakeTimers()+ const apiModule = await import('~/api') as { oidcApi: any }+ const oidcApi = apiModule.oidcApi+ setupGlobals()+ canAutomaticallyRetryOidcSignInSpy.mockReturnValue(false)++ oidcApi.callback.mockRejectedValue({+ message: 'AADSTS54005: Authorization code was already redeemed',+ })++ const wrapper = mount(OidcCallbackPage, {+ global: {+ stubs: {+ TwoFactorVerificationModal: true,+ Loader: true,+ UAlert: {+ template: '<div class="alert">{{ title }} {{ description }}</div>',+ props: ['title', 'description'],+ },+ UButton: {+ template: '<button>{{ label }}<slot /></button>',+ props: ['label', 'color', 'variant', 'to'],+ emits: ['click'],+ },+ },+ },+ })++ await flushPromises()+ vi.runAllTimers()+ await flushPromises()++ expect(oidcApi.redirect).not.toHaveBeenCalled()+ expect(wrapper.text()).toContain('We could not reconnect automatically')+ expect(wrapper.text()).toContain('Back to sign in')+ vi.useRealTimers()+ })+it('links account after two-factor verification when token is present', async () => {setupGlobals({query: { oidc_link_token: 'link-token-123' },diff --git a/docs/configuration/custom-domain.mdx b/docs/configuration/custom-domain.mdxindex c2dcea82c..3cfd84e2a 100644--- a/docs/configuration/custom-domain.mdx+++ b/docs/configuration/custom-domain.mdx@@ -13,15 +13,40 @@ This page explains how to configure a custom domain for your OpnForm instance.## Custom Domain Setup-To use a custom domain (or subdomain)with OpnForm:+To use a custom domain (or subdomain) with OpnForm:-1. Purchase a domain (if needed)+1. Purchase a domain (if needed)2. Configure DNS records to point to your OpnForm instance3. Update OpnForm configuration:- - Set `APP_URL` in `.env`+ - Set both `APP_URL` and `FRONT_URL` in `api/.env`- Set `NUXT_PUBLIC_APP_URL` and `NUXT_PUBLIC_API_BASE` in `client/.env`4. Secure with SSL certificate+For example, when the public URL is `https://forms.example.com`:++```bash+# api/.env+APP_URL=https://forms.example.com+FRONT_URL=https://forms.example.com++# client/.env+NUXT_PUBLIC_APP_URL=https://forms.example.com+NUXT_PUBLIC_API_BASE=https://forms.example.com/api+```++`FRONT_URL` is used by the backend when it creates frontend callback URLs,+including OIDC callbacks. Keep it aligned with the public frontend URL.++After changing these files, recreate the containers; a restart alone does not+load new environment values. See [Updating Environment Variables](./environment-variables#updating-environment-variables).++<Note>+ If an OIDC connection already exists, edit it afterwards, use **Use current+ app URL** to refresh its redirect URI, save it, and update the URI in your+ identity provider. Existing connections retain their previous redirect URI+ until you save a new one.+</Note>+import CloudVersion from "/snippets/cloud-version.mdx";<CloudVersion/>diff --git a/docs/configuration/oidc-sso.mdx b/docs/configuration/oidc-sso.mdxindex 1aadee685..e9ecdccc0 100644--- a/docs/configuration/oidc-sso.mdx+++ b/docs/configuration/oidc-sso.mdx@@ -11,12 +11,11 @@ description: Complete guide to configuring OpenID Connect Single Sign-On for youEnterprise license is required to add more users.</Info>-OpnForm supports OpenID Connect (OIDC) based Single Sign-On (SSO), allowing users to authenticate using their organization's identity provider (IdP) such as Azure Entra ID, Authentik, Okta, or any OIDC-compliant provider.+OpnForm supports OpenID Connect (OIDC) based Single Sign-On (SSO), allowing users to authenticate using any OIDC-compliant identity provider (IdP).<Info>- OpnForm handles OIDC redirect URLs automatically. You don't need to manually- configure redirect URLs in your OIDC provider - the system generates them- dynamically and displays them in the connection settings.+ OpnForm displays the exact callback URL for each connection. Copy that URL+ into your IdP's allowed redirect URIs; it must match exactly.</Info>## Features@@ -49,7 +48,7 @@ Before setting up OIDC SSO, ensure you have:<Step title="Get OIDC Provider Information">From your identity provider, collect the following information:- - **Issuer URL**: The base URL of your IdP (e.g., `https://idp.company.com` or `https://login.microsoftonline.com/{tenant-id}/v2.0`)+ - **Issuer URL**: The base URL of your IdP (e.g., `https://idp.company.com`)- **Client ID**: OAuth client identifier- **Client Secret**: OAuth client secret- **Email Domain**: The domain you want to use for routing (e.g., `company.com`)@@ -92,11 +91,12 @@ Before setting up OIDC SSO, ensure you have:</Step><Step title="Configure Group-to-Role Mapping (Optional)">- If your IdP provides group information in the ID token, you can map IdP groups to workspace roles:+ If your IdP provides group information in the **ID token**, you can map+ groups to workspace roles:1. In the connection settings, expand **Role Mappings**2. Click **Add Mapping**- 3. Enter the IdP group name (as it appears in your ID token)+ 3. Enter the exact value from the token's `groups` (or `group`) claim4. Select the corresponding workspace role (owner, admin, editor, or member)5. Repeat for each group you want to map@@ -104,6 +104,19 @@ Before setting up OIDC SSO, ensure you have:If a user belongs to multiple groups, the highest privilege role will be assigned. Role priority: owner > admin > editor > member.</Info>+ <Warning>+ Matching is exact and case-sensitive. Copy the raw value emitted in the+ ID token, not a display name from your IdP's administration interface+ unless that display name is itself the claim value. Many IdPs emit an+ immutable group identifier rather than a human-readable name.+ </Warning>++ <Note>+ OpnForm reads only the `groups` or `group` claim. Configure your IdP to+ include one of these claims in the **ID token**. A custom claim name or+ a claim named `roles` is not used for role mapping.+ </Note>+</Step><Step title="Configure Field Mappings (Optional)">@@ -171,27 +184,19 @@ When enabled:For more details, see the [Environment Variables](../configuration/environment-variables#oidc_force_login) documentation.-## Supported Providers--OpnForm is compatible with any OIDC-compliant identity provider, including:+## Updating a connection or changing the instance URL-- **Azure Entra ID** (formerly Azure AD)-- **Authentik**-- **Okta**-- **Keycloak**-- **Google Workspace** (via OIDC)-- Any other OIDC-compliant provider+You can edit an existing OIDC connection without deleting it.-### Azure Entra ID Specific Notes+- Leave **Client Secret** empty to retain the current secret. Enter a value only+ when rotating or replacing it.+- After changing the public URL of a self-hosted instance, update both the+ backend `APP_URL` and `FRONT_URL`, plus the frontend `NUXT_PUBLIC_APP_URL`.+ Recreate the relevant containers so the new environment values are loaded.+- Edit the connection, click **Use current app URL** below its redirect URI,+ then save. Copy the refreshed URL into your IdP's allowed redirect URIs.-- May require additional scopes (e.g., `groups`) to include groups in the ID token-- Configure group claims in Azure AD app registration → Token configuration-- Choose "Security groups" or "Directory roles" as needed--### Authentik Specific Notes--- Groups are typically included automatically in ID tokens-- Standard OIDC configuration works out of the box+See [Custom Domain](../configuration/custom-domain) and [Environment Variables](../configuration/environment-variables#updating-environment-variables) for the instance URL and container steps.## Troubleshooting@@ -214,7 +219,7 @@ OpnForm is compatible with any OIDC-compliant identity provider, including:- Redirect URI copied incorrectly- HTTPS/HTTP mismatch- **Solution**: Copy the exact redirect URI from the connection settings and ensure it's added to your IdP's allowed redirect URIs. Verify HTTPS is used in production.+ **Solution**: Copy the exact redirect URI from the connection settings and ensure it's added to your IdP's allowed redirect URIs. Verify HTTPS is used in production. If the instance URL changed, edit the connection, click **Use current app URL**, save it, and update the URL at the IdP.</Accordion>@@ -222,10 +227,24 @@ OpnForm is compatible with any OIDC-compliant identity provider, including:**Possible causes:**- Groups not included in ID token- - Group names don't match exactly- - Group claim not configured in IdP+ - The mapping value does not exactly match the value in the token+ - The IdP sent a display name where OpnForm expects an identifier, or vice versa+ - The group claim is not configured in the ID token+ - The IdP omitted groups because the user belongs to too many groups++ **Solution**: Inspect the decoded **ID token** returned for the user. Confirm it contains a `groups` or `group` claim, then copy one of its raw values exactly (including case) into the mapping. Configure the IdP to emit only the groups needed by this application if it omits a large group list.++</Accordion>++<Accordion title="Callback Says the Sign-in Attempt Was Already Used">+ OAuth authorization codes can only be exchanged once. This commonly happens+ when the callback URL is refreshed, revisited from history, or opened in a+ second tab.- **Solution**: Verify groups are included in your ID token. Check group names match exactly (case-sensitive). For Azure AD, configure group claims in app registration settings.+ **Solution**: OpnForm starts one fresh sign-in automatically. If that+ cannot be completed, select **Back to sign in** and try again. Do not+ refresh or reuse the callback URL. Clearing the browser cache is not+ necessary.</Accordion>