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.


Last update: September 29, 2022