0

当我尝试从内部 Web 服务器获取 json 时,我需要应对挑战。我从上一个问题中遵循了这一点。这是我的代码

let defaultManager: Alamofire.SessionManager = {
            let serverTrustPolicies: [String: ServerTrustPolicy] = [
                "myhttpsinternaldomain.org": .disableEvaluation
            ]

            let configuration = URLSessionConfiguration.default
            configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders

            return Alamofire.SessionManager(
                configuration: configuration,
                serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
            )
        }()

        let url = URL(string: urlString)
        let username = "user"
        let password = "password"
        let header = ["user": username, "password": password]

        defaultManager.request(url!, method: .get, headers: header).responseJSON { response in
            switch response.result {
            case .success(let value):
                let json = JSON(value)
                print("JSON: \(json)")
            case .failure(let error):
                print(error)
            }
        }

这是我收到的错误

错误域=NSURLErrorDomain 代码=-999 “取消” UserInfo={NSErrorFailingURLKey= https://myhttpsinternaldomain.org , NSLocalizedDescription=cancelled, NSErrorFailingURLStringKey= https://myhttpsinternaldomain.org }

我找到了这个,但我的项目中没有令牌。我只想使用用户名和密码或忽略挑战

请任何帮助

4

2 回答 2

5

知道了!或者更确切地说,我找到了正确的页面,让我找到了答案。 Github 页面服务器信任策略管理器使用 Alamofire 连接到自签名服务器

在 SSL 拒绝我的身份验证之后,最初我会收到 310 错误。

然后我添加了我最初发布的经理类,并收到 -999 错误,说它已“取消”。感谢上面的 Github Page 原因是因为我需要

“确保保留对新 SessionManager 实例的引用,否则当您的 sessionManager 被释放时,您的请求将全部取消。”

因此,感谢第二个 stackoverflow 页面,我创建了一个 NetworkManager 类,并在我的 alamofire 请求中调用它。

这是下面有效的代码,希望这可以节省很多时间。

// Network Manager outside view controller

        class NetworkManager {
        static let sharedInstance = NetworkManager()

        let manager: Alamofire.SessionManager = {
            let serverTrustPolicies: [String: ServerTrustPolicy] = [
                "https://mydomainthatwasdrivingmebananas.com": .pinCertificates(
                    certificates: ServerTrustPolicy.certificates(),
                    validateCertificateChain: true,
                    validateHost: true),
                "mydomainthatwasdrivingmebananas.com": .disableEvaluation
            ]

            let configuration = URLSessionConfiguration.default
            configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders

            return Alamofire.SessionManager(
                configuration: configuration,
                serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
            )
        }()
    }

然后 Alamofire 呼叫

// Inside ViewController ViewDidLoad

NetworkManager.sharedInstance.manager.request("https://mydomainthatwasdrivingmebananas.com", method: .get).responseJSON{ response in
                switch response.result {
                                case .success(let value):
                                    let json = JSON(value)
                                    print("JSON: \(json)")
                                case .failure(let error):
                                    print(error)
                                }

        }

PS JSON() 方法是 swifty JSON,以防有人感到困惑

于 2017-05-24T12:25:24.560 回答
0

您不能像在邮递员中那样在标题中发送这样的用户名和密码。您必须将它们更改为 base64。这就是邮递员在将您的凭据添加到标题时在后台执行的操作。

// Your hostname and endpoint
let hostname = "myhttpsinternaldomain.org"
let cert = "YOUR_CERT" // e.g. for cert.der, this should just be "cert"

// Set up certificates
let pathToCert = Bundle.main.path(forResource: cert, ofType: "der")
let localCertificate = NSData(contentsOfFile: pathToCert!)
let certificates = [SecCertificateCreateWithData(nil, 
localCertificate!)!]

// Configure the trust policy manager
let serverTrustPolicy = ServerTrustPolicy.pinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: true
)    
let serverTrustPolicies = [hostname: serverTrustPolicy]
let serverTrustPolicyManager = ServerTrustPolicyManager(policies: 
serverTrustPolicies)

// Configure session manager with trust policy
let defaultManager = Alamofire.SessionManager(
  configuration: URLSessionConfiguration.default,
  serverTrustPolicyManager: serverTrustPolicyManager
)

let url = URL(string: urlString)

let user = "user"

let password = "password"

let base64 = "\(user):\(password)".toBase64()



   let header = [

        "Authorization": "Basic \(base64)"
   ]

   //Added encoding type in the request. Change and try other types too. Like JSONEncoding.default
    defaultManager.request(url!, method: .get, encoding: URLEncoding.default ,headers: header).responseJSON { response in
        switch response.result {
        case .success(let value):
            let json = JSON(value)
            print("JSON: \(json)")
        case .failure(let error):
            print(error)
        }
    }

extension String {

   func toBase64() -> String {
       return Data(self.utf8).base64EncodedString()
   }
}

在此处输入图像描述

于 2017-05-23T16:27:57.980 回答