You must configure your application instance through the Clerk Dashboard for the enterprise connection(s) that you want to use. Visit the appropriate guide for your platform to learn how to configure your instance.
This example is written for Next.js App Router but it can be adapted for any React-based framework, such as React Router or Tanstack React Start.
The following example will both sign up and sign in users, eliminating the need for a separate sign-up page. However, if you want to have separate sign-up and sign-in pages, the sign-up and sign-in flows are equivalent, meaning that all you have to do is swap out the SignIn object for the SignUp object using the useSignUp() hook.
Starts the authentication process by calling SignIn.authenticateWithRedirect(params). This method requires a redirectUrl param, which is the URL that the browser will be redirected to once the user authenticates with the identity provider.
Creates a route at the URL that the redirectUrl param points to. The following example names this route /sso-callback. This route should either render the prebuilt <AuthenticateWithRedirectCallback/> component or call the Clerk.handleRedirectCallback() method if you're not using the prebuilt component.
The following example shows two files:
The sign-in page where the user can start the authentication flow.
The SSO callback page where the flow is completed.
Sign in page
SSO callback page
app/sign-in/[[...sign-in]]/page.tsx
'use client'import*as React from'react'import { useSignIn } from'@clerk/nextjs'exportdefaultfunctionPage() {const { signIn,isLoaded } =useSignIn()constsignInWithEnterpriseSSO= (e:React.FormEvent) => {e.preventDefault()if (!isLoaded) returnnullconstemail= (e.target asHTMLFormElement).email.value signIn.authenticateWithRedirect({ identifier: email, strategy:'enterprise_sso', redirectUrl:'/sign-in/sso-callback', redirectUrlComplete:'/', }).then((res) => {console.log(res) }).catch((err:any) => {// See https://clerk.com/docs/guides/development/custom-flows/error-handling// for more info on error handlingconsole.log(err.errors)console.error(err,null,2) }) }return ( <formonSubmit={(e) =>signInWithEnterpriseSSO(e)}> <inputid="email"type="email"name="email"placeholder="Enter email address" /> <button>Sign in with Enterprise SSO</button> </form> )}
app/sign-in/sso-callback/page.tsx
import { AuthenticateWithRedirectCallback } from'@clerk/nextjs'exportdefaultfunctionPage() {// Handle the redirect flow by calling the Clerk.handleRedirectCallback() method// or rendering the prebuilt <AuthenticateWithRedirectCallback/> component.// This is the final step in the custom Enterprise SSO flow.return <AuthenticateWithRedirectCallback />}
To handle both sign-up and sign-in without a separate sign-up page, the following example:
Uses the useSSO()Expo Icon hook to access the startSSOFlow() method.
Calls the startSSOFlow() method with the strategy param set to enterprise_sso and the identifier param set to the user's email address that they provided. The optional redirect_url param is also set in order to redirect the user once they finish the authentication flow.
If authentication is successful, the setActive() method is called to set the active session with the new createdSessionId. You may need to check for session tasks that are required for the user to complete after signing up.
If authentication is not successful, you can handle the missing requirements, such as MFA, using the signIn or signUp object returned from startSSOFlow(), depending on if the user is signing in or signing up. These objects include properties, like status, that can be used to determine the next steps. See the respective linked references for more information.
app/(auth)/sign-in.tsx
import { ThemedText } from'@/components/themed-text'import { ThemedView } from'@/components/themed-view'import { useSSO } from'@clerk/clerk-expo'import*as AuthSession from'expo-auth-session'import { useRouter } from'expo-router'import*as WebBrowser from'expo-web-browser'import React, { useEffect, useState } from'react'import { Platform, Pressable, StyleSheet, TextInput } from'react-native'exportconstuseWarmUpBrowser= () => {useEffect(() => {// Preloads the browser for Android devices to reduce authentication load time// See: https://docs.expo.dev/guides/authentication/#improving-user-experienceif (Platform.OS!=='android') returnvoidWebBrowser.warmUpAsync()return () => {// Cleanup: closes browser when component unmountsvoidWebBrowser.coolDownAsync() } }, [])}// Handle any pending authentication sessionsWebBrowser.maybeCompleteAuthSession()exportdefaultfunctionPage() {useWarmUpBrowser()constrouter=useRouter()const [email,setEmail] =useState('')// Use the `useSSO()` hook to access the `startSSOFlow()` methodconst { startSSOFlow } =useSSO()constonPress=async () => {try {// Start the authentication process by calling `startSSOFlow()`const { createdSessionId,setActive,signIn,signUp } =awaitstartSSOFlow({ strategy:'enterprise_sso', identifier: email,// For web, defaults to current path// For native, you must pass a scheme, like AuthSession.makeRedirectUri({ scheme, path })// For more info, see https://docs.expo.dev/versions/latest/sdk/auth-session/#authsessionmakeredirecturioptions redirectUrl:AuthSession.makeRedirectUri(), })// If sign in was successful, set the active sessionif (createdSessionId) {setActive!({ session: createdSessionId,navigate:async ({ session }) => {if (session?.currentTask) {// Handle pending session tasks// See https://clerk.com/docs/guides/development/custom-flows/authentication/session-tasksconsole.log(session?.currentTask)return }router.push('/') }, }) } else {// If there is no `createdSessionId`,// there are missing requirements, such as MFA// Use the `signIn` or `signUp` returned from `startSSOFlow`// to handle next steps } } catch (err) {// See https://clerk.com/docs/guides/development/custom-flows/error-handling// for more info on error handlingconsole.error(JSON.stringify(err,null,2)) } }return ( <ThemedViewstyle={styles.container}> <ThemedTexttype="title"style={styles.title}> Sign in with SAML </ThemedText> <ThemedTextstyle={styles.label}>Email address</ThemedText> <TextInputstyle={styles.input}value={email}onChangeText={setEmail}placeholder="Enter email"placeholderTextColor="#666666"autoCapitalize="none"keyboardType="email-address" /> <Pressablestyle={({ pressed }) => [styles.button,!email &&styles.buttonDisabled, pressed &&styles.buttonPressed, ]}onPress={onPress}disabled={!email} > <ThemedTextstyle={styles.buttonText}>Sign in with SAML</ThemedText> </Pressable> </ThemedView> )}conststyles=StyleSheet.create({ container: { flex:1, padding:20, gap:12, }, title: { marginBottom:8, }, label: { fontWeight:'600', fontSize:14, }, input: { borderWidth:1, borderColor:'#ccc', borderRadius:8, padding:12, fontSize:16, backgroundColor:'#fff', }, button: { backgroundColor:'#0a7ea4', paddingVertical:12, paddingHorizontal:24, borderRadius:8, alignItems:'center', marginTop:8, }, buttonPressed: { opacity:0.7, }, buttonDisabled: { opacity:0.5, }, buttonText: { color:'#fff', fontWeight:'600', },})
EnterpriseSSOView.swift
importSwiftUIimportClerkKitstructEnterpriseSSOView:View {@Environment(Clerk.self)privatevar clerk@Stateprivatevar email =""var body: some View {TextField("Enter email", text: $email)Button("Sign in with Enterprise SSO") {Task { awaitsignInWithEnterpriseSSO(email: email) } } } }extensionEnterpriseSSOView {funcsignInWithEnterpriseSSO(email: String) async {do {let result =tryawait clerk.auth.signInWithEnterpriseSSO(emailAddress: email)// Enterprise SSO can complete as either a sign-in or sign-up// Clerk returns a TransferFlowResult to cover both casesswitch result {case .signIn(let signIn):switch signIn.status {case .complete:dump(clerk.session)default:dump(signIn.status) }case .signUp(let signUp):switch signUp.status {case .complete:dump(clerk.session)default:dump(signUp.status) } } } catch {// See https://clerk.com/docs/guides/development/custom-flows/error-handling// for more info on error handlingdump(error) } } }
EnterpriseSSOViewModel.kt
EnterpriseSSOActivity.kt
EnterpriseSSOView.kt
import android.util.Logimport androidx.lifecycle.ViewModelimport androidx.lifecycle.viewModelScopeimport com.clerk.api.Clerkimport com.clerk.api.network.serialization.errorMessageimport com.clerk.api.network.serialization.onFailureimport com.clerk.api.network.serialization.onSuccessimport com.clerk.api.signin.SignInimport com.clerk.api.signup.SignUpimport com.clerk.api.sso.ResultTypeimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.flow.combineimport kotlinx.coroutines.flow.launchInimport kotlinx.coroutines.launchclassEnterpriseSSOViewModel : ViewModel() {privateval _uiState =MutableStateFlow<UiState>(UiState.Loading)val uiState = _uiState.asStateFlow()init {combine(Clerk.isInitialized, Clerk.userFlow) { isInitialized, user -> _uiState.value=when {!isInitialized -> UiState.Loading user !=null-> UiState.Authenticatedelse-> UiState.SignedOut } }.launchIn(viewModelScope) }funsignInWithEnterpriseSSO(email: String) { viewModelScope.launch { Clerk.auth.signInWithEnterpriseSso { this.email = email }.onSuccess {// Enterprise SSO can complete as either a sign-in or sign-up.when (it.resultType) { ResultType.SIGN_IN -> {if (it.signIn?.status == SignIn.Status.COMPLETE) { _uiState.value= UiState.Authenticated } else {// If the status is not complete, check why. User may need to// complete further steps. } } ResultType.SIGN_UP -> {if (it.signUp?.status == SignUp.Status.COMPLETE) { _uiState.value= UiState.Authenticated } else {// If the status is not complete, check why. User may need to// complete further steps. } } } }.onFailure {// See https://clerk.com/docs/guides/development/custom-flows/error-handling// for more info on error handling Log.e("EnterpriseSSO", it.errorMessage, it.throwable) } } }sealedinterfaceUiState {dataobjectLoading : UiStatedataobjectSignedOut : UiStatedataobjectAuthenticated : UiState } }