Swift & Go Quickstart

This is a quickstart guide to help you integrate Descope with your Swift & Go 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
go get github.com/descope/go-sdk

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 include BaseUrl as a parameter in your client.Config (e.g. {BaseUrl : "https://api.descope.com"}) when initializing descopeClient.

app.go
import "github.com/descope/go-sdk/descope"
import "github.com/descope/go-sdk/descope/client"
 
// Utilizing the context package allows for the transmission of context capabilities like cancellation
//      signals during the function call. In cases where context is absent, the context.Background()
//      function serves as a viable alternative.
//      Utilizing context within the Descope GO SDK is supported within versions 1.6.0 and higher.
import (
	"context"
)

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.go
descopeClient, err := client.NewWithConfig(&client.Config{ProjectID:"__ProjectID__"})
if err != nil {
    log.Println("failed to initialize: " + err.Error())
}
 
// ctx: context.Context - Application context for the transmission of context capabilities like
//        cancellation signals during the function call. In cases where context is absent, the context.Background()
//        function serves as a viable alternative.
//        Utilizing context within the Descope GO SDK is supported within versions 1.6.0 and higher.
ctx := context.Background()
 
// Fetch session token from HTTP Authorization Header
sessionToken := "xxxx"
 
authorized, userToken, err := descopeClient.Auth.ValidateSessionWithToken(ctx, sessionToken)
if (err != nil){
  fmt.Println("Could not validate user session: ", err)
} else {
  fmt.Println("Successfully validated user session: ", userToken)
}

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