2017-10-13 15 views
1

こんにちは、HTTPS URLから取得リクエストをしようとしています。しかし、私は絶えずエラーを受けています。Swift 3 HTTPS GETリクエスト

2017-10-13 18:13:43.372427+0800 VQ Smart Home[13412:2155414] Unknown class _TtC13VQ_Smart_Home16ManageUserstable in Interface 

Builderのファイル。 2017-10-13 18:13:43.403238 + 0800 VQスマートホーム[13412:2155471] TIC SSLトラストエラー[6:0x604000167680]:3:0 2017-10-13 18:13:43.403672 + 0800 VQスマートホーム[13412:2155471] NSURLSession/NSURLConnection HTTP読み込みに失敗しました (kCFStreamErrorDomainSSL、-9813) 2017-10-13 18:13:43.404000 + 0800 VQ Smart Home [13412:2155471]タスク< 8BB05664-B56E-41CA-92F7-BBAECC8008E3 >。 < 5 HTTPロードに失敗しました(エラー コード:-1202 [3:-9813]) 2017-10-13 18:13:43.404496 + 0800 VQ Smart Home [13412:2155472]タスク< 8BB05664-B56E-41CA-92F7 -BBAECC8008E3>。 5>エラーコード: -1202 エラー=オプション(エラードメイン= NSURLErrorDomainコード= -1202)このサーバーの証明書は無効です。「202.73」と思われるサーバー に接続している可能性があります。危険にさらされてあなたの 機密情報を置くことができます。」46.176” のUserInfo = {NSURLErrorFailingURLPeerTrustErrorKey =、NSLocalizedRecoverySuggestion =あなたは したいことは、サーバに接続とにかく?_kCFStreamErrorDomainKey = 3、_kCFStreamErrorCodeKey = -9813 、NSErrorPeerCertificateChainKey =( "" )、NSUnderlyingError = 0x60400025c920 {エラードメイン= kCFErrorDomainCFNetworkコード= -1202 "(null)" UserInfo = {_ kCFStreamPropertySSLClientCertificateState = 0、 kCFStreamPropertySSLPeerTrust =、 _kCFNetworkCFStreamSSLErrorOriginalValue = -9813、_kCFStreamErrorDomainKey = 3、_kCFStreamErrorCodeKey = -9813、kCFStreamPropertySSLPeerCertificates =( "" )}}、NSLocalizedDescriptionは、このサーバの証明書が無効です=あなたは 危険にあなたの機密情報を入れることができます 「202.73.46.176」のふりをしているサーバに接続されることがあります。、 NSErrorFailingURLKey = https://202.73.46.176/api/v1/user/find/all/1、 NSErrorFailingURLStringKey = https://202.73.46.176/api/v1/user/find/all/1、 NSErrorClientCertificateStateKey = 0})

のviewDidLoad

let urlstr: String = "https://202.73.46.176/api/v1/user/find/all/1" 

let request = NSMutableURLRequest(url: NSURL(string: urlstr)! as URL) 
request.httpMethod = "GET" 
let postString = "" 
request.httpBody = postString.data(using: String.Encoding.utf8) 

let task = URLSession.shared.dataTask(with: request as URLRequest) { 
    data, response, error in 
    if error != nil { 
     print("error=\(error)") 
     return 
    } 
    print("response = \(response)") 

    let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) 
    print("responseString = \(responseString)") 
} 
task.resume() 

方法

func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { 
     //Implementation 1: VERY WEAK METHOD 
     /*if challenge.previousFailureCount > 0{ 
     completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil) 
     }else{ 
     completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:challenge.protectionSpace.serverTrust!)) 
     }*/ 

     //Implementation 2: 
     var disposition: URLSession.AuthChallengeDisposition = URLSession.AuthChallengeDisposition.performDefaultHandling 
     var credential:URLCredential? 

     if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { 
      //certificate-based server credentials are used when verifying the server’s identity 
      credential = URLCredential(trust: challenge.protectionSpace.serverTrust!) 

      if (credential != nil) { 
       disposition = URLSession.AuthChallengeDisposition.useCredential 
      } 
      else{ 
       disposition = URLSession.AuthChallengeDisposition.performDefaultHandling 
      } 
     } 
     else{ 
      disposition = URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge 
     } 
     print("==============", #function," disposition: ", disposition) 
     print("==============", #function," disposition: ", credential!) 

     //completionHandler(disposition, credential); 




     //Implementation 3: 
     let serverTrust = challenge.protectionSpace.serverTrust 
     let certificate = SecTrustGetCertificateAtIndex(serverTrust!, 0) 

     // Set SSL policies for domain name check 
     let policies = NSMutableArray(); 
     policies.add(SecPolicyCreateSSL(true, (challenge.protectionSpace.host as CFString))) 
     SecTrustSetPolicies(serverTrust!, policies); 

     // Evaluate server certificate 
     var result = SecTrustResultType(rawValue: 0)! 
     SecTrustEvaluate(serverTrust!, &result) 

     let isServerTrusted:Bool = (result == SecTrustResultType.unspecified || result == SecTrustResultType.unspecified || result == SecTrustResultType.proceed) 
     print("==============",#function," isServerTrusted: ", isServerTrusted) 
     print("==============", #function," result: ", result.hashValue," SecTrustResultType.unspecified: ", SecTrustResultType.unspecified.hashValue," SecTrustResultType.proceed: ", SecTrustResultType.proceed.hashValue) 
     var certName = "" 
//  if self.isSimulatingCertificateCorruption { 
//   certName = corruptedCert 
//  } else { 
//   certName = cert 
//  } 

     // Get local and remote cert data 
     let remoteCertificateData = SecCertificateCopyData(certificate!) as Data 
     let pathToCert   = Bundle.main.path(forResource: certName, ofType: "der") 
     let localCertificate  = try! Data(contentsOf: URL(fileURLWithPath: pathToCert!)) 
     print(" remoteCertificateData: ", remoteCertificateData,"  localCertificate: ", localCertificate, "  serverTrust: ", serverTrust.debugDescription ) 

     if (remoteCertificateData == localCertificate) { //TODO:- this is strictly for tesing puposes, to allow untrusted severs. REMOVE IN PRODUCTION. 
      let credential:URLCredential = URLCredential(trust: serverTrust!) 
      completionHandler(.useCredential, credential) 
     }else if (isServerTrusted && (remoteCertificateData == localCertificate)) { 
      let credential:URLCredential = URLCredential(trust: serverTrust!) 
      completionHandler(.useCredential, credential) 
     } else { 
      completionHandler(.cancelAuthenticationChallenge, nil) 
     } 
    } 

誰かがこのtnxを修正するのを手助けできますか?サーバーがSSL証明書を持っていないため

答えて

0

私は

SecurityCertificateManager

を作成します。..良い答えを見つけました
import Foundation 
import Alamofire 


class SecurityCertificateManager { 
    static let sharedInstance = SecurityCertificateManager() 

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

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

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

この

 let service = CommanLinksUtility().getServiceAuthUrl() 
     let ticket = UserDefaults.standard.value(forKey: "servicket") as! String 
     let baseUrl = "https://12.3.3.3:5051/api/v1/user/find/all/1" 
     let header = [ "content-type" : "application/json", "url": service, "ticket" : ticket ] 

     SecurityCertificateManager.sharedInstance.defaultManager.request(baseUrl, method: .get, parameters: header as? [String : AnyObject], encoding: URLEncoding.queryString, headers: header) 
      .responseJSON { response in 
       let jsonResult = JSON(data: response.data!) 
       for anItem in jsonResult["result"].arrayValue { 

       } 

} 
のようにそれを呼び出します
0

あなたは「このサーバーの証明書が無効であるので、それは

信頼されていない、あなたがそのエラーを取得し

0

AFNETWorkingまたはAlmofireライブラリを使用することができます。あなたがあるかもしれません危険にあなたの機密情報を置くことができる「202.73.46.176」のふりをしているサーバーに接続する。 "`

だけで、エラーのこの部分は、何が起こっているか理解するのに十分なはずです。信頼できる適切な有効な証明書をインストールすると、エラーは消えてしまいます。あなたはまた、これはあなたのplist

<key>NSAppTransportSecurity</key> 
<dict> 
    <key>NSExceptionDomains</key> 
    <dict> 
     <key>yourdomain.com</key> 
     <dict> 
      <!--Include to allow subdomains--> 
      <key>NSIncludesSubdomains</key> 
      <true/> 
      <!--Include to allow HTTP requests--> 
      <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key> 
      <true/> 
      <!--Include to specify minimum TLS version--> 
      <key>NSTemporaryExceptionMinimumTLSVersion</key> 
      <string>TLSv1.1</string> 
     </dict> 
    </dict> 
</dict> 

でそれを指定することによって無視されるていることができますが、私はこれを行うだけの.plistキーのHow can I add NSAppTransportSecurity to my info.plist file?から参照サーバー

のSSL証明書を取得控えるでしょう

関連する問題