BasicAuthenticationObserver

open class BasicAuthenticationObserver

Basic Authentication Observer


The BasicAuthenticationObserver is a SAPURLSessionObserving that can be used to automatically handle cases where communication requires a BasicCredential. The component listens on the didReceive challenge SAPURLSession delegate method. The BasicAuthenticationObserver uses two delegates:

You can implement the BasicCredentialStoring to manage the BasicCredential storage. Usually this is performed in the application itself:

  1. The observer calls the delegate to store, retrieve and delete the BasicCredential.
  2. The implementer stores the BasicCredential in a secure way.
  3. The URL can be used to distinguish BasicCredentials if the application uses more resource servers using, for example, the host from the URL as a key.
func store(credential: BasicCredential, for: URL) throws -> Void {
// save the BasicCredential to a secure storage
}

func credential(for: URL) throws -> BasicCredential? {
// return the BasicCredential from the secure storage
}

func delete(for: URL) throws -> Void {
// delete the BasicCredential from the secure storage
}

When an authentication challenge occurs, BasicAuthenticationObserver first calls the BasicCredentialStoring delegate to retrieve the BasicCredential. If this step fails it calls the BasicCredentialDiscovery delegate to create a new BasicCredential.

The DefaultBasicCredentialDiscovery is a default implementation of BasicCredentialDiscovery protocol. It presents a UIAlertController with a host label and username, password UITextFields.

Usage

Initialization and registration

Initialize a BasicAuthenticationObserver

let basicAuthenticationObserver = BasicAuthenticationObserver(basicCredentialStore: self)
sapURLSessionForResource.register(basicAuthenticationObserver)

Start request to Resource URL

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

Observer to collect the necessary credential for basic authentication