Many authentication schemes involve acquiring a token and passing it in a header. Do this via Service.configure(...)
:
class MyApi: Service {
init() {
...
configure { $0.config.headers["Authorization"] = authHeader }
}
var authHeader: String? {
didSet {
// Clear any cached data now that auth has changed
wipeResources()
// Force resources to recompute headers next time they’re fetched
invalidateConfiguration()
}
}
}
When authentication succeeds:
myAPI.authToken = authTokenFromOAuthLib
…and for logout:
myAPI.authToken = nil
You will probably want a third-party lib such as p2/OAuth2 or dongri/OAuthSwift to handle the dance of acquiring an OAuth token. Once you have the token, integrate it exactly as you would any other token-based authentication. (See previous section.)
You could integrate OAuth more tightly with Siesta. For example, you could add special error handling hooks in your Siesta config to trigger a token refresh when you detect an OAuth expiration. TODO: Examples of this However, third-party libraries usually provide satisfactory mechanisms for refreshing the token outside of Siesta.
TODO: Flesh this out. Quick sketch follows.
Two approaches, not mutually exclusive:
- Use
wipeResources()
to evict all authorization-dependent data on logout. - Create new
Session
instance, and either wipe resources or discard all references to old session’s resources.
TODO: Add section describing how to limit API calls to specific hosts, to limit accidental credential exposure when resolving relative URLs
Siesta relies on the underlying networking provider, which by default is NSURLSession
, to support SSL public key pinning. There are several ways to integrate this with Siesta.
TrustKit provides certificate pinning by swizzling new behavior into NSURLSession
, and thus requires no additional Siesta configuration.
Create a custom NSURLSessionDelegate
to handle the authentication challenge, then configure an NSURLSession
with your custom NSURLSessionDelegate
— all exactly as you would without Siesta. Then pass this NSURLSession
as your networking provider when you create the Siesta service:
let certificatePinningSession = NSURLSession(
configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(),
delegate: MyCustomSessionPinningDelegate(),
delegateQueue: nil)
let myService = Service(baseURL: "http://what.ever", networking: certificatePinningSession)
For example code, see the OWASP guide. That example is for the older NSURLConnection
instead of NSURLSession
, but the code is very similar.
If you are using Siesta with Alamofire as a networking provider, you can use the Alamofire security utilities.