Skip to content

Authentication

You can configure your mobile application to access SAP Mobile Services using the following authentication methods:

API Key Only (Anonymous Access)

Applications can be configured so that no authentication challenges are sent, and all application requests are processed anonymously. This is accomplished using the API Key Only authentication mechanism.

Prerequisite

The security configuration of the mobile services app must be set to API Key Only. This generates a default API Key, which can be used in the client application.

See Configuring App Security in CF for more information.

Using API Key in the Client Application

Using Foundation Framework

Use APIKeyAuthenticationObserver from SAPFoundation to attach the API Key to all your application requests.

let apiKeyAuthenticationConfig: APIKeyAuthenticationConfig? = getAPIKeyAuthenticationConfig()
let apiKeyObserver = APIKeyAuthenticationObserver(apikeyCredentialDiscovery: DefaultAPIKeyCredentialDiscovery(using: apiKeyAuthenicationConfig), isAPIKeyAccessOnly: true)
let session = SAPURLSession()
session.register(apiKeyObserver)

//Start request to Resource URL using closure completion callbacks

let request = URLRequest(url: <#resourceURL#>)
let dataTask = session.dataTask(with: request) { data, response, error in
// Handle the error and the response
}

dataTask.resume()


//Or start request to Resource URL using `async`/`await` approach (Swift's structured concurrency)

Task {
    do {
        let request = URLRequest(url: <#resourceURL#>)
        let result = try await session.data(for: request)
        // Handle the data and response
    } catch {
        // Handle the error
    }
}

When you use API keys in your applications, ensure that they are kept secure during both storage and transmission. To help keep your API keys secure, use the obfuscate and deobfuscate functions in the Obfuscator module, as shown here.

func getAPIKeyAuthenticationConfig() -> APIKeyAuthenticationConfig? {
  let keyBytes = obfuscator.obfuscate(<API Key retrieved from mobile services>)
    let obfuscator: Obfuscating = Obfuscator()
    let key = obfuscator.deobfuscate([<Obfuscated byte array>])
    return APIKeyAuthenticationConfig(apikeys: [key], isAPIKeyAccessOnly: true, allowAnonymousAccessFlag: false)
}

Note

If you are using SAPFioriFlows in your application, you can use the APIKeyAuthenticationStep directly to achieve Anonymous Access through API Key.

Using SAP Fiori Flows Framework

You can use the APIKeyAuthenticationStep from SAPFioriFlows, to attach the API Key to all your application requests.

public var onboardingSteps: [OnboardingStep] {
    return [
        self.configuredWelcomeScreenStep(),
        CompositeStep(steps: SAPcpmsDefaultSteps.configuration),
        APIKeyAuthenticationStep(config: self.getAPIKeyAuthenticationConfig()),
        CompositeStep(steps: SAPcpmsDefaultSteps.settingsDownload),
        CompositeStep(steps: SAPcpmsDefaultSteps.applyDuringOnboard),
        ...
    ]
}

public var restoringSteps: [OnboardingStep] {
    return [
        self.configuredStoreManagerStep(),
        self.configuredWelcomeScreenStep(),
        CompositeStep(steps: SAPcpmsDefaultSteps.configuration),
        APIKeyAuthenticationStep(config: self.getAPIKeyAuthenticationConfig()),
        CompositeStep(steps: SAPcpmsDefaultSteps.settingsDownload),
        CompositeStep(steps: SAPcpmsDefaultSteps.applyDuringRestore),
        ...
    ]
}

func getAPIKeyAuthenticationConfig() -> APIKeyAuthenticationConfig? {
    let obfuscator: Obfuscating = Obfuscator()
    let key = obfuscator.deobfuscate([<Obfuscated byte array>])
    return APIKeyAuthenticationConfig(apikeys: [key], isAPIKeyAccessOnly: true, allowAnonymousAccessFlag: false)
}

Note

If you use the SAP BTP SDK Assistant for iOS to create your application, then the necessary code is automatically generated. Choose API Key Only as the authentication mechanism during app creation.

Cross Context SSO

The cross context SSO feature simplifies onboarding for users by transferring OAuth tokens from an established session to their mobile app built using the SAP BTP SDK for iOS.

For example, a user opens the SSO onboarding URL on their desktop. The user can open the native app, navigate to the QR code scanning screen, and scan the QR code before it expires. If successful, the native app will get onboarded automatically.

The user does not have to enter their credentials again.

Prerequisites

  • Your app is using OAuth2
  • An administrator has enabled Cross Context SSO in the Security tab of the Application Settings in the mobile services cockpit and shared the SSO onboarding URL with app users.

SSO Onboarding URL Behavior on Desktop and Mobile Device

When a user opens the SSO onboarding URL, they will have a different experience depending on whether they are using their desktop as opposed to a mobile device.

When a user opens the URL on their desktop, a page is displayed with a QR code containing a short-duration passcode. The user opens the app and scans the QR code with the barcode scanner before the timer expires. This triggers the onboarding flow in the app and the user is onboarded.

When a user opens the URL on their mobile device, the browser displays a page with a Next button and a timer. If the user clicks Next before the timer expires, they are prompted to open the app. On opening, the app starts the onboarding flow and the user is onboarded.

Enabling Cross Context SSO

To enable Cross Context SSO, you need to configure the WelcomeScreenStep to use JSONConfigurationProvider, and you need to set barcodeScanner as a configuration option of FUIWelcomeScreen.

let welcomeScreenStep = WelcomeScreenStep(transformer: discoveryConfigurationTransformer, providers: [JSONConfigurationProvider()])

welcomeScreenStep.welcomeScreenCustomizationHandler = { welcomeStepUI in
            ...

            if let welcomeScreen = welcomeStepUI as? FUIWelcomeScreen {
            ...
                welcomeScreen.configurationOptions = [.barcodeScanner, .discoveryService]
            }
        }

This enables opening the scanner with which the QR code can be scanned.

Add the following property to your OnboardingFlowProvider.swift:

var urlConfigurationProvider: URLConfigurationProvider? = nil

The property needs to be set in the application(_:open:options:) (or in the application(_:willContinueUserActivityWithType:) if using Universal Links) method of your UIApplicationDelegate implementation before being passed to AppDelegateDispatcher.

AppDelegateDispatcher reads the configuration data from the URL that opened the app and places this information in urlConfigurationProvider, as shown here:

// implementation of this method will be generated by SAP BTP SDK Assistant for iOS
func application(_: UIApplication, open url: URL, options _: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
          if url.absoluteString.range(of: "config=") != nil {
            let provider = URLConfigurationProvider()
            AppDelegateDispatcher.register(provider)
            let result = AppDelegateDispatcher.application(app, open: url)
            AppDelegateDispatcher.unregister(provider)
            if result == false {
                flowProvider.urlConfigurationProvider = nil
            } else {
                flowProvider.urlConfigurationProvider = provider
                window!.rootViewController = FUIInfoViewController.createSplashScreenInstanceFromStoryboard()
            }
            ...
            // regular onboarding code
            return result
        } else {
            return false
        }
}

Update the WelcomeScreenStep to use the information stored in the property, allowing the app to launch and start onboarding when the user clicks Next on the device browser.

var providers: [ConfigurationProviding] = [JSONConfigurationProvider()]
if let configProvider = self.urlConfigurationProvider {
     providers.insert(configProvider, at: 0)
}

let welcomeScreenStep = WelcomeScreenStep(transformer: discoveryConfigurationTransformer, providers: providers)
...

Note

Compile time errors may occur when using SAP BTP SDK for iOS v9.0 frameworks with apps generated using SAP BTP SDK Assistant for iOS 8.0.x or 7.x.x.

To resolve these errors, make the changes described above in OnboardingFlowProvider.swift and AppDelegate.swift.

Your app needs to support the Custom URL Scheme to enable this behavior. If you select the Enable Cross Context SSO option, the SAP BTP SDK for iOS will generate the necessary project settings on app creation.

Note

You can use Apple Universal Links rather than a Custom URL Scheme. Enable Apple Universal Links in the mobile services cockpit and add the Associated Domain capability in the Signing and Capabilities for your app target in Xcode.

For further information, see Allowing Apps and Websites to Link to Your Content.

Add the following code in the application(_:didFinishLaunchingWithOptions) method to allow the app to be opened from a browser.

        if let _ = launchOptions?[.url] as? URL {
            return true
        } else {
            // regular onboarding code
        }

Note

If you use the SAP BTP SDK Assistant for iOS to create your app, you can add cross context SSO support by enabling Cross Context SSO under OAuth Authentication. The necessary code is automatically included when the app is generated.

Note

The SAP BTP SDK for iOS presents the login screen where users enter their credentials through a browser or a WebView for standard identity providers. When integrating third-party identity providers, the SDK implementation may not suit all third-party providers. The behavior depends on how the login screen in the web page is implemented, such as opening in the same window / tab or a new browser window or a new tab.

External Browser for OAuth2 Authentication

You can configure your app to perform OAuth2 authentication and logout in a separate external browser app installed on the device, such as Google Chrome, Mozilla Firefox, or Microsoft Edge.

External browser authentication is useful when your identity provider requires a full browser (for example, to reuse an existing browser session, device certificates, or browser-based single sign-on).

Step 1: Specify the Configuration

You configure the preferred browser with the PreferredBrowser key. When present, the SDK routes the OAuth2 authentication and logout URLs to the specified browser.

You can provide PreferredBrowser value in two forms:

  • A plain browser name (String) for one of the browsers the SDK recognizes.
  • A custom URL scheme template for a browser, provided as a dictionary.

Using a Recognized Browser Name

To use one of the recognized browsers, set PreferredBrowser to one of the following string values:

Value Browser
chrome Google Chrome
firefox Mozilla Firefox
edge Microsoft Edge
safari Safari

For example, to use Google Chrome, set PreferredBrowser to chrome.

Using a Custom URL Scheme Template for a Browser

To use a browser that is not in the list above, provide PreferredBrowser as a dictionary with the following keys:

Key Required Description
urlSchemeTemplate Yes A URL template containing the literal {url} placeholder. When launching the browser, the SDK replaces {url} with the authentication (or logout) URL.
name Yes A human-readable name for the browser, used for logging and diagnostics.

Providing the Configuration

The SDK reads the PreferredBrowser key from your application configuration. You can supply it through a mobile device management (MDM) managed configuration, or add it to the file configuration (ConfigurationProvider.plist) of your app.

The following example shows the PreferredBrowser entries in a ConfigurationProvider.plist.

To use a recognized browser by name:

<key>PreferredBrowser</key>
<string>chrome</string>

To use a custom URL scheme template:

<key>PreferredBrowser</key>
<dict>
    <key>name</key>
    <string>Firefox</string>
    <key>urlSchemeTemplate</key>
    <string>firefox://open-url?url={url}</string>
</dict>

Step 2: Update AppDelegate

The app must handle the callback URL that the external browser uses to redirect back to the app after authentication and logout. Forward it to the AppDelegateDispatcher:

// in AppDelegate
extension AppDelegate {

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
        return AppDelegateDispatcher.application(app, open: url, options: options)
    }
}

Step 3: Update OnboardingFlowProvider

In onboardingSteps and restoringSteps, add OAuth2AuthenticationStep() without any parameters:

OAuth2AuthenticationStep()

Step 4: Update OnboardingErrorHandler

Handle the external-browser errors OAuth2Error.preferredBrowserNotInstalled and OAuth2Error.couldNotOpenPreferredBrowser so the user is informed when the preferred browser is not installed or cannot be opened.

  1. In onboardFailed(), add the following case to the switch error {}:

    case OAuth2Error.preferredBrowserNotInstalled(_), OAuth2Error.couldNotOpenPreferredBrowser(_):
        showAlertWith(error: error)
    
  2. In restoreFailed(), add one more case to the switch error {}:

    case OAuth2Error.preferredBrowserNotInstalled(_), OAuth2Error.couldNotOpenPreferredBrowser(_):
        alertController.title = LocalizedStrings.Onboarding.failedToLogonTitle
        alertController.message = error.localizedDescription
        alertController.addAction(UIAlertAction(title: LocalizedStrings.Onboarding.retryTitle, style: .default) { _ in
            completionHandler(.retry)
        })
    

Step 5: Update Info.plist

Before launching the preferred browser, the SDK checks whether that browser is installed. For this check to succeed, the browser's URL scheme must be listed in the LSApplicationQueriesSchemes (Queried URL Schemes) array in your app's Info.plist.

For a recognized browser name, add the corresponding scheme:

PreferredBrowser value Scheme to add
chrome googlechrome
firefox firefox
edge microsoft-edge-https
safari https

For example:

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>firefox</string>
    <string>googlechrome</string>
    <string>microsoft-edge-https</string>
</array>

For a custom URL scheme template, add the scheme portion of your urlSchemeTemplate — that is, the part before ://. For example, for the template firefox://open-url?url={url} the scheme is firefox, so add:

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>firefox</string>
</array>

Add an entry for each browser you intend to support.

Note

For the external browser to open successfully, your identity provider's redirect URI must use a custom scheme registered by your app, so that the browser can redirect back to the app after authentication and logout. Make sure the preferred browser is installed on the device.


Last update: October 19, 2026