Last week we in Bite #223 and #224 we covered an example "Standard Setup" for new apps. Since those Bites were published, readers have been asking many questions, requesting more information about how all these things fit together.
Today we'll answer one of those questions in more depth: Authentication. Let's dive in.
Who? Again it's me, Jake Marsh! I write this thing.
Like we covered before, the heart of our HTTP "stack" is built around the Moya framework (Bite #150). One of the neat parts about Moya is how it lets us customize how it works. One way is through an "request closure". As the name implies, this closure's job is to create the actual NSURLRequest that will be sent.
Here's an example implementation. Inside we can set HTTP headers, and modify the URL request in any way we want. This makes adding authentication super simple.
Here we set a "Bearer" token as the Authorization header.
let requestClosure = { (endpoint: RxMoya.Endpoint<StewardAPI>, done: NSURLRequest -> Void) in
let request = endpoint.urlRequest.mutableCopy() as! NSMutableURLRequest
if let token = SharedKeycard.token {
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
done(request)
}
The SharedKeycard is simply a singleton that holds the auth token:
func lookForTokenInKeychain() -> String? { /* not important */ }
public class Keycard : NSObject {
public var token: String? = nil
public override init() {
super.init()
token = lookForTokenInKeychain()
}
}
public let SharedKeycard = Keycard()
Finally, we simply pass in our custom request closure when creating our Moya "provider":
let StewardAPI = RxMoyaProvider<StewardAPI>(
requestClosure: requestClosure
)
A quick shout out to reader Justin Williams who wrote in asking for more information about how authentication fits into this puzzle.
Have any questions about how all this fits together? Want to see some other developer's example setup? Don't be shy! hello@littlebitesofcocoa.com. Any and all comments/questions are welcome!