如何使用TLS和自签名证书在本地服务器中使用Alamofire安全上传文件?

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

我能够使用带有ATS Allow Arbitrary Loads和以下代码片段的Alamofire 5在本地服务器(在node.js中实现)上成功上传文件:

struct httpBinResponse: Decodable { let url: String }
let url = "http://10.0.0.2:443/upload"
let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
guard let fileURL : URL = path.appendingPathComponent("F06F34EC-0BFD-4201-8405-7CED956CA299.zip") else {return}
AF.upload(multipartFormData:
    {(multipart) in multipart.append(fileURL, withName: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream" )},
    to: url)
    .responseDecodable(of: httpBinResponse.self) { response in
        debugPrint(response)
}

我能够在本地服务器上切换到HTTPS,并且可以使用自签名的ca / client和服务器证书通过Postman上传文件。我已经阅读了有关自签名证书固定的帖子,但是不确定是否需要固定或认证。

在具有自签名证书和Alamofire的本地服务器中涉及TLS的最佳做法是什么?

编辑5/4/20:遵循来自不同来源的建议,我通过添加以下内容取得了进步:

struct Certificates {
    static let ca: SecCertificate = Certificates.certificate(filename: "ca")

    private static func certificate(filename: String) -> SecCertificate {
        let filePath = Bundle.main.path(forResource: filename, ofType: "der")!
        let data = try! Data(contentsOf: URL(fileURLWithPath: filePath))
        let certificate = SecCertificateCreateWithData(nil, data as CFData)!
        return certificate
    }
}

并且在我的课堂内,我添加了:

private let secureSession: Session = {
    let certificates : [SecCertificate] = [Certificates.ca]

    let pinnedCertEvaluator = PinnedCertificatesTrustEvaluator(certificates: certificates,
                                                               acceptSelfSignedCertificates: true,
                                                               performDefaultValidation: false,
                                                               validateHost: false)
    let manager = ServerTrustManager(evaluators: ["10.0.0.2": pinnedCertEvaluator])
    let configuration = URLSessionConfiguration.af.default

    return Session(configuration: configuration, serverTrustManager: manager)
}()

添加以上内容后,我可以使用https上传文件。我不确定为什么必须将performDefaultValidationvalidateHost设置为false以避免得到Alamofire.AFError.serverTrustEvaluationFailed。这是正确的方法吗?我要弄清楚的另一点是,为什么只需要ca根证书进行固定?

ios swift ssl https alamofire
1个回答
0
投票

我已经实现了类似的功能:

  1. 将您自己签名的证书复制到XCode项目中。让我们将此证书称为“ myCert.der”

  2. 使用您的签名证书设置Alamofire安全会话管理器。将会是这样。

    var secureSessionManager = Alamofire.SessionManager()
    func configureAlamoFireSSLPinning() {
    
      let pathToCert = Bundle.main.path(forResource: "myCert", ofType: "der")
      let localCertificate:NSData = NSData(contentsOfFile: pathToCert!)!
    
      if #available(iOS 10.3, *) {
        let STP = ServerTrustPolicy.pinPublicKeys(
        publicKeys: [SecCertificateCopyPublicKey(SecCertificateCreateWithData(nil, localCertificate)!)!],
        validateCertificateChain: true,
        validateHost: true)
    
        let serverTrustPolicies = [
         "myhost.com": STP
        ]
    
        secureSessionManager = Alamofire.SessionManager(
        configuration: URLSessionConfiguration.default,
        serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies))
      }
    }
    
  3. 调用该函数来设置您的安全会话管理器:configureAlamoFireSSLPinning()

  4. 使用此alamofire安全会话管理器发出请求。通过此管理员提出的所有请求将是安全的:

    secureSessionManager.request("https://host.com/myrequest", method:.get).responseJSON { response in 
    
     switch response.result {
      case .success(let value):
       //Do stuff
      case .failure(let error):
       print(error)
    
     }
    }
    

    有关更多信息,您可以访问Alamofire的安全性文档:https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#security

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