Skip to main content

Authentication flows

Use Auth for sign-in and sign-up flows, and to manage sessions. You can access auth with clerk.auth.

Sign in

Sign in with password

Sign in directly with an identifier (email, phone, or username) and password:

var signIn = try await clerk.auth.signInWithPassword(
  identifier: "user@email.com",
  password: "secretpassword"
)

Sign in with OTP (email)

Send an to the supplied email, and then verify the code.

var signIn = try await clerk.auth.signInWithEmailCode(emailAddress: "user@email.com")
signIn = try await signIn.verifyCode("123456")

Sign in with OTP (phone)

Send an to the supplied phone number, and then verify the code.

var signIn = try await clerk.auth.signInWithPhoneCode(phoneNumber: "+1234567890")
signIn = try await signIn.verifyCode("123456")

Sign in with OAuth

Sign in using an OAuth provider (e.g., Google, GitHub, see all providers):

var result = try await clerk.auth.signInWithOAuth(provider: .google)
var result = try await clerk.auth.signInWithApple()

See the Sign in with Apple guide for native iOS setup.

Sign in with ID token

Sign in with an ID token from a provider:

var result = try await clerk.auth.signInWithIdToken(
  idToken,
  provider: .apple
)

Sign in with passkey

Sign in using a passkey:

var signIn = try await clerk.auth.signInWithPasskey()

To control how iOS presents the passkey request, create the passkey sign-in first and then authenticate it. The following example tries a modal passkey request and falls back to AutoFill-assisted passkey suggestions:

var signIn = try await clerk.auth.createPasskeySignIn()

do {
  signIn = try await signIn.authenticateWithPasskey()
} catch let error as ASAuthorizationError where error.code == .canceled {
  // No passkey was available on this device, or the user dismissed the sheet.
  signIn = try await signIn.authenticateWithPasskey(autofill: true)
}

iOS shows AutoFill suggestions when the user focuses a text field with .textContentType(.username). authenticateWithPasskey(autofill: true) doesn't return until the user selects a suggestion, so run it in a task and cancel the task if the user leaves the screen or picks another sign-in method.

Sign in with biometrics

Sign in using a biometric credential that was enrolled on the current app installation:

var signIn = try await clerk.auth.signInWithBiometrics()

See the biometric sign-in guide to learn how to enroll, use, and revoke biometric credentials.

Sign in with Enterprise SSO

Sign in using Enterprise SSO:

var result = try await clerk.auth.signInWithEnterpriseSSO(emailAddress: "user@company.com")

To control how the identity provider (IdP) page opens, such as in the user's default browser, start Enterprise SSO yourself and complete it when your app receives the callback URL:

let signIn = try await clerk.auth.startEnterpriseSSO(emailAddress: "user@company.com")

guard let url = signIn.firstFactorVerification?.externalVerificationRedirectUrl.flatMap(URL.init(string:)),
      await UIApplication.shared.open(url) else {
  // Show an error and let the user try again.
  return
}

// Later, when your app receives the callback URL:
let result = try await signIn.completeEnterpriseSSO(callbackURL: callbackURL)

completeEnterpriseSSO(callbackURL:) returns a TransferFlowResult, which is .signIn or .signUp depending on whether the user already has an account. To skip sign-up creation, pass transferable: false to completeEnterpriseSSO(callbackURL:transferable:), which then always returns .signIn.

When you open the URL yourself, register your callback URL's scheme under CFBundleURLTypes in your app's Info.plist so the callback can reach your app. The callback URL is the redirectUrl you pass to startEnterpriseSSO(emailAddress:), or redirectUrl in RedirectConfig, which defaults to {bundleIdentifier}://callback.

Sign in with ticket

Sign in using a ticket generated from the Backend API:

var signIn = try await clerk.auth.signInWithTicket(ticket)

If the Backend API created the sign-in token with org_id, Clerk activates that Organization for the resulting session. After sign-in succeeds, the Organization ID is available from Clerk.shared.session?.lastActiveOrganizationId.

Send an email link to the supplied email address. After the user opens the link, handle the callback with clerk.handle(url).

let signIn = try await clerk.auth.signInWithEmailLink(emailAddress: "user@email.com")
// Show a message that tells the user to check their email.

Sign in with identifier

Start a sign-in with an identifier (email, phone, or username):

// Email
var signIn = try await clerk.auth.signIn("user@email.com")
// Phone
var signIn = try await clerk.auth.signIn("+1234567890")
// Username
var signIn = try await clerk.auth.signIn("johndoe")

Continue an existing sign-in

Use these methods when you already have a SignIn from clerk.auth.signIn() or clerk.auth.currentSignIn, and want to complete it with a specific factor or provider.

Send and verify email code

Send the user an via email to verify their sign-in. Then verify the code that the user supplies:

signIn = try await signIn.sendEmailCode()
signIn = try await signIn.verifyCode("123456")

Send the user an email link to verify their sign-in. After the user opens the link, handle the callback with clerk.handle(url).

signIn = try await signIn.sendEmailLink()
// Show a message that tells the user to check their email.

Send and verify phone code

Send the user an via SMS to verify their sign-in. Then verify the code that the user supplies:

signIn = try await signIn.sendPhoneCode()
signIn = try await signIn.verifyCode("123456")
signIn = try await signIn.authenticateWithPassword("secretpassword")

Authenticate with OAuth

Authenticate with an OAuth provider (e.g., Google, GitHub, see all providers):

var result = try await signIn.authenticateWithOAuth(provider: .google)
var result = try await signIn.authenticateWithEnterpriseSSO()
var result = try await signIn.authenticateWithApple()
signIn = try await signIn.authenticateWithIdToken(
  idToken,
  provider: .apple
)
signIn = try await signIn.authenticateWithPasskey()

Multi-factor authentication

After completing , if multi-factor authentication (MFA) or Device Trust requires a second factor, use these methods to complete the . The examples assume you already have a SignIn from a sign-in flow.

MFA with phone code

Send and verify an MFA code via SMS:

signIn = try await signIn.sendMfaPhoneCode()
signIn = try await signIn.verifyMfaCode(
  "123456",
  type: .phoneCode
)

MFA with email code

Send and verify an MFA code via email:

signIn = try await signIn.sendMfaEmailCode()
signIn = try await signIn.verifyMfaCode(
  "123456",
  type: .emailCode
)

Device Trust can verify a new device with an email link. When a sign-in has a status of .needsClientTrust and its supportedSecondFactors has an .emailLink factor, send the link. After the user opens the link, handle the callback with clerk.handle(url).

signIn = try await signIn.sendMfaEmailLink()
// Show a message that tells the user to check their email.

MFA with TOTP (authenticator app)

Verify using a TOTP code from an authenticator app:

signIn = try await signIn.verifyMfaCode(
  "123456",
  type: .totp
)

MFA with backup code

Verify using a backup code:

signIn = try await signIn.verifyMfaCode(
  "backup123",
  type: .backupCode
)

Password reset

The Clerk iOS SDK provides methods to reset user passwords via email or phone verification.

Password reset with email

Reset password using email verification:

var signIn = try await clerk.auth.signIn("user@email.com")
signIn = try await signIn.sendResetPasswordEmailCode()
signIn = try await signIn.verifyCode("123456")
signIn = try await signIn.resetPassword(
  newPassword: "newpassword",
  signOutOfOtherSessions: true
)

Password reset with phone

Reset password using phone verification:

var signIn = try await clerk.auth.signIn("+1234567890")
signIn = try await signIn.sendResetPasswordPhoneCode()
signIn = try await signIn.verifyCode("123456")
signIn = try await signIn.resetPassword(
  newPassword: "newpassword",
  signOutOfOtherSessions: true
)

Sign up

Create a new sign-up

Create a new account:

var signUp = try await clerk.auth.signUp(
  emailAddress: "newuser@email.com",
  password: "secretpassword",
  firstName: "John",
  lastName: "Doe",
  username: "johndoe",
  phoneNumber: "+1234567890",
  legalAccepted: true
)

Update a sign-up

Update sign-up information:

signUp = try await signUp.update(
  emailAddress: "newuser@email.com",
  password: "secretpassword",
  firstName: "John",
  lastName: "Doe",
  username: "johndoe",
  phoneNumber: "+1234567890",
  legalAccepted: true
)

Sign up with OAuth

Sign up using an OAuth provider (e.g., Google, GitHub, see all providers):

var result = try await clerk.auth.signUpWithOAuth(provider: .google)
var result = try await clerk.auth.signUpWithApple()

See the Sign in with Apple guide for native iOS setup.

Sign up with ID token

Sign up using an ID token:

var result = try await clerk.auth.signUpWithIdToken(
  idToken,
  provider: .apple,
  firstName: "John",
  lastName: "Doe"
)
var result = try await clerk.auth.signUpWithEnterpriseSSO(emailAddress: "user@company.com")

Sign up with ticket

Sign up using a ticket, such as one from an application invitation:

var signUp = try await clerk.auth.signUpWithTicket(ticket)

Continue an existing sign-up

Use these methods when you already have a SignUp from clerk.auth.signUp() or clerk.auth.currentSignUp and want to complete it with a specific factor or provider.

Send and verify email via OTP

Send the user an via email to verify their account. Then verify the code that the user supplies:

signUp = try await signUp.sendEmailCode()
signUp = try await signUp.verifyEmailCode("123456")

Send the user an email link to verify their account. After the user opens the link, handle the callback with clerk.handle(url).

signUp = try await signUp.sendEmailLink()
// Show a message that tells the user to check their email.

Send and verify phone via OTP

Send the user an via SMS to verify their account. Then verify the code that the user supplies:

signUp = try await signUp.sendPhoneCode()
signUp = try await signUp.verifyPhoneCode("123456")

Hosted authentication

Hosted authentication opens Clerk's Account Portal in a browser authentication session. Account Portal supports the sign-in and sign-up methods enabled for your Clerk application. When authentication completes, the SDK closes the browser session and activates the new session in your app.

The following example opens the Account Portal sign-in page:

try await clerk.auth.startHostedAuth()

Pass .signUp to open the sign-up page first:

try await clerk.auth.startHostedAuth(mode: .signUp)

startHostedAuth() accepts the following parameters:

  • mode - The Account Portal page to open first. Defaults to sign-in.
  • redirectUrl - A custom native callback with a non-HTTP URL scheme; http, https, and universal-link callbacks are rejected. Defaults to Clerk's configured redirect URL, which is <bundle-identifier>://callback unless overridden.
  • prefersEphemeralWebBrowserSession - Whether the browser should use an ephemeral session. Defaults to false.

startHostedAuth() returns the Session that the SDK activated. The result is discardable; clerk.user reflects the signed-in user after the call completes. If the user dismisses the browser or authentication fails, the method throws.

See the hosted authentication guide for setup instructions and tradeoffs.

Current sign-in/sign-up

Access the in-progress sign-in or sign-up stored on the client for multi-step flows.

Current sign-in

let currentSignIn = clerk.auth.currentSignIn
let currentSignUp = clerk.auth.currentSignUp

Session management

The Clerk iOS SDK provides methods to manage user sessions, including signing out, switching sessions, and revoking sessions.

Sessions

Retrieve all sessions for the current client:

let sessions = clerk.auth.sessions

Get session token

Retrieve the user's :

guard let token = try await clerk.auth.getToken() else { return }

Use this token when calling your backend to authenticate the request:

var request = URLRequest(url: url)
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")

Check authorization

Use checkAuthorization() on a Session to check whether that session's user has a Role or Permission in the , has a Plan or Feature, or has reverified recently. Pass one Role, Permission, Plan, or Feature, optionally with a reverification requirement, or a reverification requirement alone. When you pass both, it returns true only if both pass.

guard let session = clerk.session else { return }

let isAdmin = session.checkAuthorization(role: "org:admin")
let canDeleteInvoices = session.checkAuthorization(permission: "org:invoices:delete", reverification: .moderate)
let hasWidgets = session.checkAuthorization(feature: "widgets")

It returns false when the session has no user, and for Role and Permission checks when there is no Active Organization. To check the current session, use clerk.has() instead. See Authorization checks for every condition and the reverification presets.

Reverify a session

Reverification asks a signed-in user to verify their identity again before a sensitive action. Check whether the user verified recently with clerk.has(reverification:), or rely on your backend's response, and then start a reverification on the current session:

guard let session = clerk.session else { return }

var verification = try await session.startVerification(level: .firstFactor)

Pass .secondFactor to verify only a second factor, or .multiFactor to verify both a first and a second factor. Use the level your backend requires. The returned SessionVerification has a status of .needsFirstFactor, .needsSecondFactor, or .complete, and lists the factors the user can use in supportedFirstFactors and supportedSecondFactors.

Verify a first factor

When the status is .needsFirstFactor, verify one of the factors in supportedFirstFactors. Each of the following is a separate option, so call only the one for the factor the user chooses:

// Password
verification = try await session.verifyWithPassword("secretpassword")

// Email code
if let emailAddressId = verification.supportedFirstFactors?.first(where: { $0.strategy == .emailCode })?.emailAddressId {
  verification = try await session.sendEmailCode(emailAddressId: emailAddressId)
  verification = try await session.verifyWithEmailCode(code: "123456")
}

// Phone code
if let phoneNumberId = verification.supportedFirstFactors?.first(where: { $0.strategy == .phoneCode })?.phoneNumberId {
  verification = try await session.sendPhoneCode(phoneNumberId: phoneNumberId)
  verification = try await session.verifyWithPhoneCode(code: "123456")
}

// Passkey
verification = try await session.verifyWithPasskey()

// Biometric credential enrolled on this app installation
verification = try await session.verifyWithBiometrics(reason: "Verify your identity to continue.")

A user-verified passkey or a biometric credential can also satisfy a second-factor requirement, depending on your instance configuration. Biometric reverification requires a credential enrolled with the default .biometryCurrentSet policy. See the biometric sign-in guide for details.

Reset the password during reverification

If the user can't verify with their password, for example because verifyWithPassword(_:) failed when Clerk found the password in a data breach, verify with a reset password code and set a new password. Offer this when supportedFirstFactors includes a .resetPasswordEmailCode or .resetPasswordPhoneCode factor.

if let emailAddressId = verification.supportedFirstFactors?.first(where: { $0.strategy == .resetPasswordEmailCode })?.emailAddressId {
  verification = try await session.sendResetPasswordEmailCode(emailAddressId: emailAddressId)
  verification = try await session.verifyWithResetPasswordEmailCode(
    code: "123456",
    newPassword: "newsecretpassword",
    signOutOfOtherSessions: true
  )
}

For a phone number, use sendResetPasswordPhoneCode(phoneNumberId:) and verifyWithResetPasswordPhoneCode(code:newPassword:signOutOfOtherSessions:). If the verification still needs a second factor, Clerk sets the new password once the user verifies that factor.

Verify a second factor

When the status is .needsSecondFactor, verify one of the factors in supportedSecondFactors. Each of the following is a separate option, so call only the one for the factor the user chooses:

// Authenticator app
verification = try await session.verifyWithTOTP(code: "123456")

// SMS code
if let phoneNumberId = verification.supportedSecondFactors?.first(where: { $0.strategy == .phoneCode })?.phoneNumberId {
  verification = try await session.sendMfaPhoneCode(phoneNumberId: phoneNumberId)
  verification = try await session.verifyWithMfaPhoneCode(code: "123456")
}

// Backup code
verification = try await session.verifyWithBackupCode(code: "backup123")

// Passkey or biometric credential
verification = try await session.verifyWithPasskey(level: .secondFactor)
verification = try await session.verifyWithBiometrics(level: .secondFactor)

Refresh the session token

When the status is .complete, request a new session token before calling your backend, so the token carries the updated verification age. Biometric reverification clears cached tokens for you.

let token = try await session.getToken(.init(skipCache: true))

Set current session

Set the current session and optionally the :

try await clerk.auth.setActive(
  sessionId: sessionId,
  organizationId: organizationId
)

Revoke session

Revoke a specific session:

let revokedSession = try await clerk.auth.revokeSession(session)

Sign out

Sign out the current user:

// Sign out from all sessions.
try await clerk.auth.signOut()

// Sign out from a specific session.
try await clerk.auth.signOut(sessionId: sessionId)

Observe auth events

clerk.auth.events is an AsyncStream of AuthEvent values that reports authentication changes as they happen, including changes from Clerk's prebuilt views.

.task {
  for await event in clerk.auth.events {
    switch event {
    case .signInCompleted(let signIn):
      print("Sign-in completed: \(signIn.id)")
    case .signUpCompleted(let signUp):
      print("Sign-up completed: \(signUp.id)")
    case .signInNeedsContinuation(let signIn):
      print("A callback returned a sign-in that needs more steps: \(signIn.id)")
    case .signUpNeedsContinuation(let signUp):
      print("A callback returned a sign-up that needs more steps: \(signUp.id)")
    case .signedOut(let session):
      print("Signed out of session \(session.id)")
    case .accountDeleted:
      print("Account deleted")
    case .sessionChanged(let oldValue, let newValue):
      print("Session changed from \(oldValue?.id ?? "nil") to \(newValue?.id ?? "nil")")
    case .tokenRefreshed:
      print("Session token refreshed")
    }
  }
}

The events are:

  • .signInCompleted(signIn:) and .signUpCompleted(signUp:): Clerk accepted a completed sign-in or sign-up. The new session might still be pending, for example while the user has session tasks to complete. Hosted authentication doesn't send these events, so observe .sessionChanged(oldValue:newValue:) instead.
  • .signInNeedsContinuation(signIn:) and .signUpNeedsContinuation(signUp:): A Clerk callback, such as an email link, returned a sign-in or sign-up that needs more steps. Continue the flow with the attached object.
  • .signedOut(session:): A session ended. Signing out of all sessions sends one event per session.
  • .accountDeleted: The current user deleted their account.
  • .sessionChanged(oldValue:newValue:): The current session changed, including when a user signs in, signs out, or switches sessions, and when Clerk updates the current session.
  • .tokenRefreshed(token:): Clerk refreshed the session token.

Deep linking

Handle email link callbacks in your SwiftUI app:

.onOpenURL { url in
  Task {
    do {
      try await clerk.handle(url)
    } catch {
      // Show an error and let the user request a new link.
    }
  }
}

Email links open your app from the Mail app or a browser, so register your callback URL's scheme under CFBundleURLTypes in your app's Info.plist. The callback URL is redirectUrl in RedirectConfig, which defaults to {bundleIdentifier}://callback. If you pass a redirectUri to sendEmailLink() or sendMfaEmailLink(), register that URL's scheme instead and complete the link yourself, because clerk.handle(url) only recognizes redirectUrl.

clerk.handle(url) returns false for any other URL, so you can route it yourself. That includes the callback from startEnterpriseSSO(emailAddress:), which you complete with completeEnterpriseSSO(callbackURL:).

If your app routes deep links itself, complete a pending email link flow with completeMagicLink(). Pass the callback URL, or its flow_id and approval_token query values:

let result = try await clerk.auth.completeMagicLink(callbackURL: url)

switch result {
case .signIn(let signIn):
  print("Sign-in status: \(signIn.status)")
case .signUp(let signUp):
  print("Sign-up status: \(signUp.status)")
}

Send the email link from the same app installation that completes it, because the SDK stores the flow's verifier locally when it sends the link. The SDK keeps the verifier for 10 minutes, and only for the most recent link, so it can't complete an older or expired link. If completion fails, send a new link.

Feedback

What did you think of this content?

Last updated on