将iOS应用程序连接到使用Alamofire在localhost上运行的api时,证书无效
我正在尝试连接到本地主机上运行的API,以便在iOS模拟器中测试我的应用程序。我要走了 NSLocalizedDescription=此服务器的证书无效。 您可能正在连接假装为“127.0.0.1”的服务器 这可能会使您的机密信息面临风险。, NSErrorFailingURLKey=, NSErrorFailingURLStringKey=, NSErrorClientCertificateStateKey=0 我正在使用阿拉莫菲尔。没有帮助。这似乎是过时的旧版本的阿拉莫菲尔 My info.plist已包含将iOS应用程序连接到使用Alamofire在localhost上运行的api时,证书无效,ios,ssl,alamofire,Ios,Ssl,Alamofire,我正在尝试连接到本地主机上运行的API,以便在iOS模拟器中测试我的应用程序。我要走了 NSLocalizedDescription=此服务器的证书无效。 您可能正在连接假装为“127.0.0.1”的服务器 这可能会使您的机密信息面临风险。, NSErrorFailingURLKey=, NSErrorFailingURLStringKey=, NSErrorClientCertificateStateKey=0 我正在使用阿拉莫菲尔。没有帮助。这似乎是过时的旧版本的阿拉莫菲尔 My info.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
售后服务客户:
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)
}
}
}
以下是我得到的完整输出:
通过完成处理程序获取职位2017-06-19 14:22:15.770616-0400
WallAppiOS[28605:9092279][]
nw_coretls_回调_握手_消息_块_调用_3
继续握手:[-9812]2017-06-19 14:22:15.770
WallAppiOS[28605:9092321]NSURLSession/NSURLConnection HTTP加载
获取帖子时出现失败(kCFStreamErrorDomainSSL,-9813)错误:
可选(错误域=NSURLErrorDomain代码=-1202“的证书
此服务器无效。您可能正在连接到
假装是“127.0.0.1”,这会让你
信息有风险。“UserInfo={NSLocalizedDescription=证书
此服务器的“”无效。您可能正在连接到
假装是“127.0.0.1”,这可能会让你
风险信息,NSLocalizedRecoverysSuggestion=您想
是否仍要连接到服务器?,kCFStreamErrorDomainKey=3,
NSUnderlyingError=0x7a3627c0{Error Domain=KCFerrorDomain=KCF网络
代码=-1202“(空)”
UserInfo={kCFStreamPropertySSLClientCertificateState=0,
_KCFnetworkCfStreamsSrorOriginalValue=-9813,kCFStreamErrorCodeKey=-9813,kCFStreamErrorDomainKey=3,KCFStreamPropertySlPeerTrust=,,
KCFStreamPropertySLpeerCertificates=(
“”)},kCFStreamErrorCodeKey=-9813,NSErrorFailingURLStringKey=,,
NSErrorPeerCertificateChainKey=(
“”),NSErrorClientCertificateStateKey=0,
NSURlerErrorFailingUrlPeerTrustErrorKey=,
NSErrorFailingURLKey=})
在本例中,我使用
serverTrustPolicyManager
来处理与ssl非认证服务器的连接,我使用单例来处理我的应用程序中的所有连接。您必须声明sessionManager
,如Alamofire github页面所述
确保保留对新SessionManager实例的引用,
否则,您的请求将在
sessionManager已解除分配
希望这能有所帮助我将Reinermian的答案与另一个问题中的一个答案结合起来 视图控制器:
class TableViewController: UIViewController {
let postClient = PostServiceClient.sharedInstance
override func viewDidLoad() {
super.viewDidLoad()
postClient.getPosts()
}
}
class TableViewController: UIViewController {
let postClient = PostServiceClient.sharedInstance
override func viewDidLoad() {
super.viewDidLoad()
postClient.sessionManager.delegate.sessionDidReceiveChallenge = { session, challenge in
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, let trust = challenge.protectionSpace.serverTrust {
disposition = URLSession.AuthChallengeDisposition.useCredential
credential = URLCredential(trust: trust)
} else {
if challenge.previousFailureCount > 0 {
disposition = .cancelAuthenticationChallenge
} else {
credential = self.postClient.sessionManager.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
}
return (disposition, credential)
}
postClient.getPosts()
}
}
服务客户端:
class PostServiceClient {
static let sharedInstance: PostServiceClient = PostServiceClient()
var sessionManager : SessionManager!
init() {
self.sessionManager = SessionManager(configuration: URLSessionConfiguration.default)
}
static let url = URL.init(string: "https://127.0.0.1:8000/post/")
// Methods 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)
}
}
}
您如何获得服务器证书?看起来你必须关闭阿拉莫菲尔的证书登记。ATS要求您不要使用HTTP,但它与证书无关。证书检查是一个从根开始的链cert@Wingzero您知道如何关闭证书检查吗?不知道,但您可以查找信任策略设置或搜索switch@MatthewDrill我将尝试安装带有节点的本地服务器并对其进行测试,我会发布我的结果。我很高兴看到你明白了,恭喜!
class PostServiceClient {
static let sharedInstance: PostServiceClient = PostServiceClient()
var sessionManager : SessionManager!
init() {
self.sessionManager = SessionManager(configuration: URLSessionConfiguration.default)
}
static let url = URL.init(string: "https://127.0.0.1:8000/post/")
// Methods 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)
}
}
}