Social Login (OAuth) with Mobile SDKs

Descope supports many social logins such as Google, Facebook, Microsoft, etc. You can find the currently supported list of social logins in the Descope console at Settings>Authentication Methods>Social Login (OAuth). The Descope console has the defaults set for all social logins. You can customize these by configuring the social logins with your company account.

Client SDK

Install SDK

// 1. Within XCode, go to File > Add Packages
// 2. Search for the URL of the git repo: https://github.com/descope/swift-sdk
// 3. Configure your desired dependency rule
// 4. Click Add Package

Import and initialize SDK

import DescopeKit
import AuthenticationServices
 
do {
    Descope.setup(projectId: "__ProjectID__")
    print("Successfully initialized Descope")
} catch {
    print("Failed to initialize Descope")
    print(error)
}

Start OAuth

The first step in OAuth is to start the oauth process with the Identity Provider of your choice such as Google, Facebook, Microsoft etc. For this step you need call oauth start function from your app client after user clicks on social login icon.

// Args:
//   provider: social identity provider for authenticating the user. Supported values include OAuthProvider.facebook, OAuthProvider.github, OAuthProvider.google, OAuthProvider.microsoft, OAuthProvider.gitlab and OAuthProvider.apple. The current list can be found at https://github.com/descope/core-js-sdk/blob/main/src/sdk/oauth/types.ts in the OAuthProviders array.
let provider = OAuthProvider.facebook
//   redirectURL: URL to return to after successful authentication with the social identity provider. You need to implement this page to access the token and finish oauth process (token exchange). The token arrives as a query parameter named 'code'.
let redirectURL = "exampleauthschema://auth.company.com/handle-oauth"
 
guard let session = Descope.sessionManager.session else { return }
var signInOptions: [SignInOptions] = [
    .customClaims(["name": "{{user.name}}"]),
    .mfa(refreshJwt: session.refreshJwt),
    .stepup(refreshJwt: session.refreshJwt)
]
 
do {
  let authURL = try await Descope.oauth.start(provider: provider, redirectURL: redirectURL, options: signInOptions)
  guard let authURL = URL(string: authURL) else { return }
  print("Successfully Initiated OAuth Authentication")
} catch {
  print("Failed to Initiate OAuth Authentication")
  print(error)
}

Finish OAuth

After successful authentication with your IdP the user is redirected to the redirect_url that you provide in the oauth start function above. Your application should extract the code from the redirect_url and perform token exchange as shown below.

// Args:
//   authURL: the authURL generated from the Start OAuth
let authURL = "xxxxx"
 
do {
  let session = ASWebAuthenticationSession(
    url: authURL,
    callbackURLScheme: "exampleauthschema") { callbackURL, error in
 
    guard let url = callbackURL else {return}
    let component = URLComponents(url: url, resolvingAgainstBaseURL: false)
    guard let code = component?.queryItems?.first(where: {$0.name == "code"})?.value else { return }
 
    // Exchange code for session
    Task {
      do {
        let descopeSession = try await Descope.oauth.exchange(code: code)
        print("Successfully completed OAuth Authentication")
        print(descopeSession as Any)
      } catch {
        print("Failed to complete OAuth Authentication")
        print(error)
      }
    }
  }
  session.presentationContextProvider = self
  session.prefersEphemeralWebBrowserSession = true
  session.start()
} catch {
  print("Failed to complete OAuth Authentication")
  print(error)
}

Native OAuth

When running in iOS or Android, you can leverage the Sign in with Apple and Sign in with Google features to show a native authentication view that allows the user to login using the account they are already logged into on their device.

Before you can use these features, you will need to configure your application to support them. For iOS, you will need to complete the following Sign in with Apple configuration steps. For Android, you will need to complete the following configuration steps.

After configuration, you can use the following code to initiate the native authentication flow:

<Tab value="Swift">
```swift
// Swift currently supports only iOS native authentication
do {
    showLoading(true)
    let authResponse = try await Descope.oauth.native(provider: .apple, options: [])
    let session = DescopeSession(from: authResponse)
    Descope.sessionManager.manageSession(session)
    showHomeScreen()
} catch DescopeError.oauthNativeCancelled {
    showLoading(false)
    print("Authentication canceled")
} catch {
    showError(error)
}

Session Validation

The final step of completing the authentication with Descope is to validate the user session. Descope provides rich session management capabilities, including configurable session timeouts and logout functions. You can find the details and sample code for client session validation here.

Checkpoint

Your application is now integrated with Descope. Please test with sign-up or sign-in use case.

Need help?
Was this helpful?

On this page