【问题标题】:Swift: Adding SSL key to URLRequestSwift:将 SSL 密钥添加到 URLRequest
【发布时间】:2018-04-29 09:00:15
【问题描述】:

我正在尝试创建一个 URLRequest,但我需要在请求中添加 SSL 密钥和密码,但我没有找到任何如何完成此操作的示例。

这是我的要求:

func requestFactory(request:URLRequest, completion:@escaping (_ data:Data?)->Void){  
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, urlRequestResponse, error) in

    if error != nil{
        completion(data)
    }
})
task.resume()

}

非常感谢您的帮助。

【问题讨论】:

    标签: ios iphone ssl swift4 xcode9


    【解决方案1】:

    斯威夫特 4 假设您自己购买了 SSL 证书,Google 如何在终端中使用 OpenSSL 将您的 SSL 捆绑证书(.crt 文件)转换为 .der 格式。找到您在文件系统中创建的 .der 文件并将其拖到 Xcode 中的项目文件夹中。接下来,转到您的项目根目录并在 Build Phases 下,单击下拉列表“Copy Bundle Resources”,然后单击 + 按钮将 .der 文件添加到资源列表中。

    接下来,您需要创建一个实现 URLSessionDelegate 的类(在我的例子中,我称之为 URLSessionPinningDelegate),当您制定 URLSession 调用时,您将把这个类作为委托传递。 您应该查看如何实现 SSL 证书固定以获取有关如何实现此类的说明。这个网站here 对如何做到这一点有一个完美而实用的解释。

    以下是如何设置会话和任务的示例。当您调用 request.setValue 时,密码将在 URLRequest 的 Header 中传递,因此也请查看该文档。一旦您弄清楚 SSL 证书固定并设置后端以验证您的用户密码并为您的客户端证书设置信任,这应该可以帮助您开始。

    if let url = NSURL(string: "https://www.example.com") { // Your SSL server URL
    var request = URLRequest(url: url as URL)
    let password = "" // Your password value
    request.setValue("Authorization", forHTTPHeaderField: password)
    
    let session = URLSession(
    configuration: URLSessionConfiguration.ephemeral,
    delegate: URLSessionPinningDelegate(),
    delegateQueue: nil)
    

    添加会话和请求参数后,您的代码将如下所示:

    let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
                if error != nil {
                    print("error: \(error!.localizedDescription): \(error!)")
                } else if data != nil {
                    if let str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) {
                        print("Received data:\n\(str)")
                    } else {
                        print("Unable to convert data to text")
                    }
                }
            })
    
            task.resume()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多