Swift & Ruby Quickstart

This is a quickstart guide to help you integrate Descope with your Swift & Ruby application. Follow the steps below to get started.

Add the DescopeKit package

Next, we need to add the DescopeKit package (our Swift SDK) using the Swift package manager.

  • Within XCode, go to File > Add Packages and search for the URL of the git repo: https://github.com/descope/swift-sdk.
  • Then, configure your desired dependency rule and click "Add Package."

Import Frontend SDK

Next step is to import the DescopeKit package

AppDelegate.swift
import DescopeKit

Configure Descope with a custom Project ID

Configure Descope in the scene function of the SceneDelegate.swift. A Descope Project ID is required to initialize the SDK. You can find this ID on the project page in the Descope Console.

Note

You can also add the optional baseUrl parameter if you're utilizing a CNAME within your Descope project (ex: https://auth.company.com).

AppDelegate.swift
import UIKit
import DescopeKit
 
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
 
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // initialize the Descope SDK before using it
        Descope.setup(projectId: "__ProjectID__")
 
        // show home screen if user is already logged in, otherwise show authentication screen
        let initialViewController: UIViewController
        if let session = Descope.sessionManager.session, !session.refreshToken.isExpired {
            initialViewController = AppInterface.homeScreen
        } else {
            initialViewController = AppInterface.authScreen
        }
 
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = initialViewController
        window?.makeKeyAndVisible()
 
        return true
    }
 
    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        // pass any incoming Universal Links to the current flow in case we're
        // using Magic Link authentication in the flows
        guard userActivity.activityType == NSUserActivityTypeBrowsingWeb, let url = userActivity.webpageURL else { return false }
        DescopeFlow.current?.resume(with: url)
        return true
    }
}

Add the Flow URL

You'll need to get your flowURL, which is the URL where your authentication flow is hosted on the web (eg. https://example.com/login).

AuthScreen.swift
let url = URL(string: "https://api.descope.com/login/\(Descope.config.projectId)?flow=sign-up-or-in")!

Call the startFlow function

The 'startFlow' function starts the authentication process with a custom flow url.

AuthScreen.swift
/// Creates a new DescopeFlowViewController, loads the flow into it, and pushes
/// it onto the navigation controller stack
func showFlow() {
    // create a new flow object
    let url = URL(string: "https://api.descope.com/login/\(Descope.config.projectId)?flow=password")!
    let flow = DescopeFlow(url: url)
 
    // create a new DescopeFlowViewController and start loading the flow
    let flowViewController = DescopeFlowViewController()
    flowViewController.delegate = self
    flowViewController.start(flow: flow)
 
    // push the view controller onto the navigation controller
    navigationController?.pushViewController(flowViewController, animated: true)
}
 
/// This action is called when the user taps the Sign In button
@IBAction func didPressSignIn() {
    print("Starting sign in with flow")
    showFlow()
}

Create a UI component to trigger the startFlow function

Here, we implement a Button that when clicked, calls the start flow function we just wrote.

AuthScreen.xib
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="5AU-rI-FZH" userLabel="Button">
    <rect key="frame" x="32" y="346" width="329" height="48"/>
    <constraints>
        <constraint firstAttribute="height" relation="greaterThanOrEqual" constant="48" id="VxW-y0-ini"/>
        <constraint firstAttribute="height" constant="48" id="vak-nB-FJq"/>
    </constraints>
    <color key="tintColor" name="AccentColor"/>
    <state key="normal" title="Button"/>
    <buttonConfiguration key="configuration" style="filled" title="Sign In">
        <fontDescription key="titleFontDescription" name="Verdana" family="Verdana" pointSize="17"/>
        <color key="baseForegroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
    </buttonConfiguration>
    <connections>
        <action selector="didPressSignIn" destination="-1" eventType="touchUpInside" id="Wa5-at-WG8"/>
    </connections>
</button>

Utilize the Swift SDK Session Management Functions

Descope provides the sessionManager to check if the user is authenticated or get user data such as email, userId, etc. You can use these to customize the user experience:

  • isAuthenticated: is user authenticated?
  • user: user object that contains all user attributes (email, name, etc.)
  • me: updates the managed session user details and returns it
  • logout: logs the user out by revoking the active session and clearing it from the session manager/Keychain storage
AuthScreen.swift
extension SimpleFlowController: DescopeFlowViewControllerDelegate {
    func flowViewControllerDidUpdateState(_ controller: DescopeFlowViewController, to state: DescopeFlowState, from previous: DescopeFlowState) {
        print("Flow state changed to \(state) from \(previous)")
    }
    
    func flowViewControllerDidBecomeReady(_ controller: DescopeFlowViewController) {
        // in this example we don't need to handle the ready event because we're
        // just showing the flow immediately without preloading it or anything
    }
    
    func flowViewControllerShouldShowURL(_ controller: DescopeFlowViewController, url: URL, external: Bool) -> Bool {
        // we return true so that the DescopeFlowViewController does its builtin behavior
        // of opening the URL in the user's default browser app
        return true
    }
    
    func flowViewControllerDidCancel(_ controller: DescopeFlowViewController) {
        // in this example the cancel button isn't shown because the DescopeFlowViewController
        // isn't at the root of its navigation controller stack, and the user can simply
        // tap the built-in Back button to leave the flow screen
    }
    
    func flowViewControllerDidFail(_ controller: DescopeFlowViewController, error: DescopeError) {
        // errors will usually be .networkError or .flowFailed
        print("Authentication failed: \(error)")
        showError(error)
    }
    
    func flowViewControllerDidFinish(_ controller: DescopeFlowViewController, response: AuthenticationResponse) {
        // authentication succeeded so we create a new DescopeSession, give it to the session
        // manager, and transition to the user to the home screen
        print("Authentication finished")
        let session = DescopeSession(from: response)
        Descope.sessionManager.manageSession(session)
        showHome()
    }
}

At this point, you're done with the frontend. If you would like to also handle Session Management in your backend, keep on reading!

Install Backend SDK

Install the SDK with the following command:

Terminal
gem install descope

Import and Setup Backend SDK

You'll need import and setup all of the packages from the SDK.

If you're using a CNAME with your Descope project, make sure to export the Base URL (e.g. export DESCOPE_BASE_URI="https://api.descope.com") when initializing descope_client.

app.rb
require 'descope'
 
descope_client = Descope::Client.new(
  {
    project_id: '__ProjectID__'
  }
)

Implement Session Validation

You will need to then fetch the session token from the Authorization header of each request, and use the SDK to validate the token.

The frontend SDK will store the session token in either a cookie or your browser's local storage. If using a cookie, the token will be sent to your app server automatically with every request.

app.rb
# Validate the session. Will raise if expired
begin
  jwt_response = descope_client.validate_session('session_token')
rescue AuthException => e
  # Session expired
end
 
# If validate_session raises an exception, you will need to refresh the session using
jwt_response = descope_client.refresh_session('refresh_token')
 
# Alternatively, you could combine the two and
# have the session validated and automatically refreshed when expired
jwt_response = descope_client.validate_and_refresh_session('session_token', 'refresh_token')
 
session_token = jwt_response[Descope::Mixins::Common::'session_token'].fetch('jwt')  
refresh_token = jwt_response[Descope::Mixins::Common::'refresh_token'].fetch('jwt')

Congratulations

Now that you've got the authentication down, go focus on building out the rest of your app!


Checkpoint

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

Need help?

Customize

Now that you have the end-to-end application working, you can choose to configure and personalize many different areas of Descope, including your brand, style, custom user authentication journeys, etc. We recommend starting with customizing your user-facing screens, such as signup and login.

Was this helpful?

On this page