• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

ios - 使用 Alamofire 将 iOS 应用程序连接到在 localhost 上运行的 api 时证书无效

[复制链接]
菜鸟教程小白 发表于 2022-12-13 01:45:41 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我正在尝试连接到在 localhost 上运行的 API,以便可以在 iOS 模拟器中测试我的应用程序。我来了

NSLocalizedDescription=The certificate for this server is invalid. You might be connecting to a server that is pretending to be “127.0.0.1” which could put your confidential information at risk., NSErrorFailingURLKey=https://127.0.0.1:8000/post/, NSErrorFailingURLStringKey=https://127.0.0.1:8000/post/, NSErrorClientCertificateStateKey=0

我正在使用 AlamofireThis similar question没有帮助。与旧版本的 Alamofire 相比,它似乎已经过时了。

我的 info.plist 已经包含

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

如何暂时禁用证书要求,以便在 localhost 上测试我的应用程序?

这是我在更改服务器信任策略后的代码,如其中一个答案所建议的那样

View Controller :

class TableViewController: UIViewController {
    let postClient = PostServiceClient.sharedInstance

    override func viewDidLoad() {
        super.viewDidLoad()
        postClient.getPosts()
    }
}

PostServiceClient:

import Alamofire

class PostServiceClient {

    static let sharedInstance: PostServiceClient = PostServiceClient()

    var sessionManager : SessionManager!

    init() {
        let serverTrustPolicies: [String: ServerTrustPolicy] = [
            "https://127.0.0.1:8000/" : .disableEvaluation
        ]

        self.sessionManager =  SessionManager(configuration: URLSessionConfiguration.default,
                                              serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
        )
    }
    static let url = URL.init(string: "https://127.0.0.1:8000/post/")

    // Method to get posts from the wall
    func getPosts(){
        print("Getting posts with completion handler")
        var request = URLRequest(url: PostServiceClient.url!)
        request.httpMethod = "GET"
        self.sessionManager.request(request).responseJSON { (response) in
            guard response.result.isSuccess else {
                print("Error while getting posts: \(String(describing: response.result.error))")
                return
            }
            guard let responseJSON = response.result.value as? [String: Any],
                let results = responseJSON["results"] as? [[String: Any]] else {
                print("Invalid response recieved from service")
                return
            }
            print(responseJSON)
        }

    }
}

这是我得到的完整输出:

Getting posts with completion handler 2017-06-19 14:22:15.770616-0400 WallAppiOS[28605:9092279] [] nw_coretls_callback_handshake_message_block_invoke_3 tls_handshake_continue: [-9812] 2017-06-19 14:22:15.770 WallAppiOS[28605:9092321] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813) Error while getting posts: Optional(Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “127.0.0.1” which could put your confidential information at risk." UserInfo={NSLocalizedDescription=The certificate for this server is invalid. You might be connecting to a server that is pretending to be “127.0.0.1” which could put your confidential information at risk., NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, NSUnderlyingError=0x7a3627c0 {Error Domain=kCFErrorDomainCFNetwork Code=-1202 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, _kCFNetworkCFStreamSSLErrorOriginalValue=-9813, _kCFStreamErrorCodeKey=-9813, _kCFStreamErrorDomainKey=3, kCFStreamPropertySSLPeerTrust=, kCFStreamPropertySSLPeerCertificates=( "" )}}, _kCFStreamErrorCodeKey=-9813, NSErrorFailingURLStringKey=https://127.0.0.1:8000/post/, NSErrorPeerCertificateChainKey=( "" ), NSErrorClientCertificateStateKey=0, NSURLErrorFailingURLPeerTrustErrorKey=, NSErrorFailingURLKey=https://127.0.0.1:8000/post/})



Best Answer-推荐答案


在此示例中,我使用 serverTrustPolicyManager 来处理与 ssl 未认证服务器的连接,我使用单例来处理我的应用程序中的所有连接,您必须声明 sessionManager正如 Alamofire github 页面所说的那样

Make sure to keep a reference to the new SessionManager instance, otherwise your requests will all get cancelled when your sessionManager is deallocated.

    class exampleNetworkClient {

        static let sharedInstance: exampleNetworkClient = exampleNetworkClient()

        var sessionManager : SessionManager?

        init() {
            let serverTrustPolicies: [String: ServerTrustPolicy] = [
                "https://127.0.0.1:8000" : .disableEvaluation 
            ]

            self.sessionManager =  SessionManager(configuration: URLSessionConfiguration.default,
                                  serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
            )
        }

        static let portalUrl = URL.init(string:"https://127.0.0.1:8000/exampleserviceUrl")

    func exampleMethod()
    {
        var request = URLRequest(url: iOSETKClient.portalUrl!)
        request.httpMethod = "GET"

        //Important Note that you need to use your custom session manager
        self.sessionManager!.request(request).responseString { (response) in
            ///...RESPONSE LOGIC...///

        }
    }
}

希望对你有帮助

关于ios - 使用 Alamofire 将 iOS 应用程序连接到在 localhost 上运行的 api 时证书无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44621671/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap