Certificate pinning and Alamofire
1. Alamofire and URLSession.
both help you to make network requests in Swift.
Main advantage for Alamofire:
- Certificate pinning. It can take some time to sort this out and build this yourself.
Asymmetric cryptography: The second phase uses public-key cryptography or asymmetric cryptography. This is a cryptographic system that uses pairs of keys: Public keys, which are widely disseminated and private keys, which only the owner knows.
The third phase uses symmetric-key cryptography, where you use the same key for both encryption of plaintext and decryption of ciphertext.
In other words, you configure the app to reject all but one or a few predefined certificates or public keys. Whenever the app connects to a server, it compares the server certificate with the pinned certificate(s) or public key(s). If and only if they match, the app trusts the server and establishes the connection.
You usually add a service’s certificate or public key at development time. In other words, your mobile app should include the digital certificate or the public key within your app’s bundle. This is the preferred method, since an attacker cannot taint the pin.
- Requests retrying. When a request fails for example because of an authentication failure, you can easily refresh your authentication token and invoke the same request again without touching the implementation code.
- The syntax for building up requests is a lot more elegant and easier to use. It saves you from a lot extra code and makes validation and error handling a lot easier.
- Example
AF.request("https://api.mywebserver.com/v1/board", method: .get, parameters: ["title": "New York Highlights"])
.validate(statusCode: 200..<300)
.responseDecodable { (response: DataResponse) in
switch response.result {
case .success(let board):
print("Created board title is \(board.title)") // New York Highlights
case .failure(let error):
print("Board creation failed with error: \(error.localizedDescription)")
}
}enum Error Swift.Error case requestFailed
}
// Build up the URL
var components = URLComponents(string: "https://api.mywebserver.com/v1/board")!
components.queryItems = ["title": "New York Highlights"].map { (key, value) in
URLQueryItem(name: key, value: value)
}
// Generate and execute the request
let request = try! URLRequest(url: components.url!, method: .get)
URLSession.shared.dataTask(with: request) { (data, response, error) in
do {
guard let data = data,
let response = response as? HTTPURLResponse, (200 ..< 300) ~= response.statusCode,
error == nil else {
// Data was nil, validation failed or an error occurred.
throw error ?? Error.requestFailed
}
let board = try JSONDecoder().decode(Board.self, from: data)
print("Created board title is \(board.title)") // New York Highlights
} catch {
print("Board creation failed with error: \(error.localizedDescription)")
}
}
Comments
Post a Comment