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

SceneDelegate.swift
import DescopeKit
import SwiftUI
import UIKit

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).

SceneDelegate.swift
import DescopeKit
import SwiftUI
import UIKit
 
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
 
    var window: UIWindow?
 
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        Descope.config = DescopeConfig(projectId: "__ProjectID__")
 
        UserDefaults.standard.set(false, forKey: "_UIConstraintBasedLayoutLogUnsatisfiable")
 
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
 
        let contentView = ContentView().environment(\.managedObjectContext, context)
 
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()
        }
    }
 
    func sceneDidDisconnect(_ scene: UIScene) {}
    func sceneDidBecomeActive(_ scene: UIScene) {}
    func sceneWillResignActive(_ scene: UIScene) {}
    func sceneWillEnterForeground(_ scene: UIScene) {}
    func sceneDidEnterBackground(_ scene: UIScene) {
        (UIApplication.shared.delegate as? AppDelegate)?.saveContext()
    }
}
 
struct ContentView: View {}

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).

SceneDelegate.swift
struct ContentView: View {
	var flowURL = "https://auth.descope.io/login/__ProjectID__";
}

Call the startFlow function

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

SceneDelegate.swift
struct ContentView: View {
    var flowURL = "https://auth.descope.io/login/__ProjectID__";
 
    func startFlow (flowURL: String, completionHandler: @escaping (Bool, DescopeError?) -> Void) async throws {
        Task {
            do {
                let runner = await DescopeFlowRunner(flowURL: flowURL)
                let authResponse = try await Descope.flow.start(runner: runner)
                let session = DescopeSession(from: authResponse)
                Descope.sessionManager.manageSession(session)
                completionHandler(true, nil)
            } catch let descopeErr as DescopeError {
                print(descopeErr)
                completionHandler(false, descopeErr)
            }
        }
    }
}

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.

SceneDelegate.swift
struct ContentView: View {
	// ...
	// ...
 
	var body: some View {
            VStack() {
                Button(action: {
                    Task.init {
                        try await startFlow(flowURL: flowURL)
                            { result, error in
                                if result == true{}
                                else {
                                    if let unwrappedError = error {
                                        print(unwrappedError)
                                    }
                                }
                            }
                    }
                }) {
                    Text("Get started")
                }
            }
        };
}

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

At this point, you're done with the frontend. If you'd like more detail into frontend Session Management, check out our SDK. If you would like to also handle Session Validation in your backend, keep on reading!

SceneDelegate.swift
struct ContentView: View {
	// ...
	// ...
	
	let session = Descope.sessionManager.session
 
    func isAuthenticated(session: DescopeSession?) -> Bool {
        if (session == nil) {
            return false
        }
        return session!.refreshToken.isExpired;
    }
    
    func getUser(session: DescopeSession?) -> String {
        let user = session!.user
        return user
    }
 
    func updateUserDetails(session: DescopeSession?) {
        let userResponse = try await Descope.auth.me(refreshJwt: session!.refreshToken)
        return Descope.sessionManager.updateUser(userResponse)
    }
 
    func logout() {
        guard let refreshJwt = Descope.sessionManager.session?.refreshJwt else { return }
        try await Descope.auth.logout(refreshJwt: refreshJwt)
        Descope.sessionManager.clearSession()
    }
 
	var body: some View {
		VStack() {
			if isAuthenticated(session: session) {
				Text("Welcome")
				Text(getUser(session: session).email ?? "No email available")
			} else {
				Text("Please log in")
			}
			Button(action: {
				Task.init {
					try await startFlow(flowURL: flowURL)
						{ result, error in
							if result == true{}
							else {
								if let unwrappedError = error {
									print(unwrappedError)
								}
							}
						}
				}
			}) {
				Text("Get started")
			}
		}
	};
}

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