HI I wanted to implement the SSL pinning using public keys & I'm using Alamofire 4.8.2 Below is the code for that
func testWithAlmofire(){
let serverTrustPolicies:[String:ServerTrustPolicy] = [
"example.com": .pinPublicKeys(publicKeys: ServerTrustPolicy.publicKeys(), validateCertificateChain: true, validateHost: true)
]
sessionManager = SessionManager(
serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
)
sessionManager.request("https://example.com").response{ res in
if res.response != nil{
self.displayAlert(withTitle: "Test Result",
message: "Pinning validation succeeded")
}else{
self.displayAlert(withTitle: "Test Result",
message: "Pinning validation Failed")
}
}
}
Please help me if I'm doing anything wrong.
I'm using something like that, I hope this helps
class NetworkingManager {
static let shared = NetworkingManager()
private init() {
sharedSession = enableCertificatePinning()
}
var sharedSession: Session?
func enableCertificatePinning() -> Session {
func getCertificates() -> [SecCertificate] {
let certs = ["AmazonExample1", "AmazonExample2"]
var certificates = [SecCertificate]()
certs.forEach { cert in
let url = Bundle.main.url(forResource: cert, withExtension: "cer")!
let localCertificate = try! Data(contentsOf: url) as CFData
if let certificate = SecCertificateCreateWithData(nil, localCertificate) {
certificates.append(certificate)
}
}
return certificates
}
let certificates: [SecCertificate] = getCertificates()
let trustPolicy = PinnedCertificatesTrustEvaluator(
certificates: certificates,
validateHost: true)
let trustPolicies = [certificateUrl: trustPolicy,
"https://example.com": trustPolicy,
"https://example2.com": trustPolicy]
let policyManager = ServerTrustManager(evaluators: trustPolicies)
return Session(
configuration: .default,
serverTrustManager: policyManager)
}
}
You can use like that
func exampleRequisiton(someBody: exampleBody, completion: @escaping (Result<responseExample, NetworkErrors>, _ message: String?) -> Void){
guard let url = URL(string: InviteUrl) else {
completion(.failure(.invalidUrl), nil)
return
}
var request = getDefaultRequest(url, .post)
request.httpBody = try? JSONEncoder().encode(someBody)
NetworkingManager.shared.sharedSession?.request(request).validate().responseDecodable(of: DefaultResponse.self, decoder: defaultDecoder) { data in
switch data.result {
case let .success(data):
completion(.success(data), nil)
case let .failure(error):
completion(.failure(.genericError), nil)
}
}
}
I tried to use an example with all options used in a requisition(body, header) because I think you gonna need to use this in some moment. the code bellow is those objects used in every requisition that I create separately
var HttpHeaders: HTTPHeaders {
let version = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? ""
return [
"SomeHeader if you have": "example"
]
}
func getDefaultRequest(_ url:URL, _ method:HTTPMethod) -> URLRequest{
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = method.rawValue
request.headers = HttpHeaders
return request
}
enum NetworkErrors: Error {
case authError
case genericError
case invalidUrl
case serverMessage
}
struct responseExample:Codable{
let systemTimeMillis: Int?
let message: String?
let status: Int?
}
struct exampleBody: Codable {
var example: String
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.