在alamofire manager class swift中添加公钥固定

问题描述 投票:0回答:1

这是我的alamofire经理,如何在其上添加公钥固定?请帮助我,我无法知道在我的代码中执行此操作的方法,如果可能的话,我需要逐步解释如何使用具有所有请求的AFManager

class AFManager : NSObject{


///without headers (post)
//used this to registration
class func requestPOSTURL(_ strURL : String, params : [String : 
AnyObject]?, success:@escaping (JSON) -> Void, failure:@escaping (Error) -> Void){
URLCache.shared.removeAllCachedResponses()
Alamofire.request(strURL, method: .post, parameters: params, encoding: URLEncoding.httpBody).responseJSON { (responseObject) -> Void in

    //print(responseObject)

    if responseObject.result.isSuccess {
        let resJson = JSON(responseObject.result.value!)
        success(resJson)
    }
    if responseObject.result.isFailure {
        let error : Error = responseObject.result.error!
        failure(error)
    }
}
}


///// response string (post)
//used this in login // used in change password
class func strRequestPOSTURL(_ strURL : String, params : [String : String]?, headers : [String : String]?, success:@escaping (JSON) -> Void, failure:@escaping (Error) -> Void){
URLCache.shared.removeAllCachedResponses()
Alamofire.request(strURL, method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: headers).responseJSON { (response) in
    //print(response)

    if response.result.isSuccess {
        let resJson = JSON(response.result.value!)
        success(resJson)
    }
    if response.result.isFailure {
        let error : Error = response.result.error!

        failure(error)
    }

}

  }

}

我看到了这个示例,但不知道该怎么做以及我应该把代码放在哪里,请看下面的链接:https://infinum.co/the-capsized-eight/ssl-pinning-revisited

swift request alamofire public-key-pinning
1个回答
1
投票

我建议使用TrustKit。它是一个专用库,可以与NSURLSession(包括Alamofire)一起使用。根据您的使用情况,可能只需向Info.plist添加一些值即可。

证书固定与任何安全措施相同,不是您应该自己实现的,但您应该使用经过验证的库。


0
投票

使用TrustKit与Alamofire进行SSL固定。这里我包含了API Manager类。这将帮助您解决使用Alamofire与TrustKit。

class ApiManager: SessionDelegate{

  var sessionManager: SessionManager? 

  override init(){
        super.init()
        initReachibility()
        sessionManager = SessionManager.init(configuration: URLSessionConfiguration.ephemeral, delegate: self)
    }

  override func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        // Call into TrustKit here to do pinning validation
        if TrustKit.sharedInstance().pinningValidator.handle(challenge, completionHandler: completionHandler) == false {
            // TrustKit did not handle this challenge: perhaps it was not for server trust
            // or the domain was not pinned. Fall back to the default behavior
            completionHandler(.cancelAuthenticationChallenge, nil)
        }
    }

  func makeRequestAlamofire(route:URL, method:HTTPMethod, autherized:Bool, parameter:Parameters,header:[String:String], callback: @escaping (APIResult<Data>) -> Void){

        sessionManager?.request(route,method: method,parameters:parameter, encoding: JSONEncoding.default,headers:headers ).validate(statusCode: 200..<300)
            .validate(contentType: ["application/json"]).responseData { response in
                //Pin Validtion returner
                guard response.error == nil else {
                    // Display Error Alert
                    print("Result Pinning validation failed for \(route.absoluteString)\n\n\(response.error.debugDescription)")
                    return
                }
                switch response.result {
                  case .success(let val):
                    print("Success")
                  case .failure(let error):
                    print("Faild")
                }
        }
    }
}

有关完整教程,请参阅this link


0
投票
let serverTrustPolicies: [String: ServerTrustPolicy] = [
     // or `pinPublicKeys`
    "test.example.com": .pinCertificates(
        certificates: ServerTrustPolicy.certificates(),
        validateCertificateChain: true,
        validateHost: true
    ),
    "insecure.expired-apis.com": .disableEvaluation
]

let sessionManager = SessionManager(
    serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
)

© www.soinside.com 2019 - 2024. All rights reserved.