Я начинаю разработку iOS. Я хочу получить доступ к некоторым данным с сервера IBM Domino с проверкой подлинности. Код может только вернуть страницу входа в систему. Кто-нибудь знает, что случилось? (И простите за мой английский)Swift 3 аутентификация URLSession на сервере IBM Domino
Вот мой код, чтобы получить данные:
class URLSessionTest: NSObject, URLSessionDelegate {
let user = "myUser"
let password = "myPwd"
let url = URL.init(string: "https://www.example.com/Test.nsf/0/91182C6C9EEE0414C12580A300312D1A?Opendocument")
func getData() {
var request = URLRequest.init(url: url!)
request.httpMethod = "POST"
request.timeoutInterval = 30.0
let parameters = ["Username": user, "Password": password] as Dictionary<String, String>
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch let error {
print("request serialization error: \(error.localizedDescription)")
}
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
let task = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
if error != nil {
print ("dataTask error: \(error!.localizedDescription)")
}
if let myresponse = response as? HTTPURLResponse {
print ("dataTask response: \(myresponse)")
myresponse.statusCode
}
let myval = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!
print("dataTask data: \(myval)")
})
task.resume()
}
И делегаты:
open func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void){
print ("challenge \(challenge.protectionSpace.authenticationMethod)")
var disposition: URLSession.AuthChallengeDisposition = .useCredential
var credential:URLCredential?
let defaultCredential = URLCredential(user: user, password: password, persistence: URLCredential.Persistence.none)
if challenge.previousFailureCount > 0 {
print ("cancel authentication challenge")
disposition = .cancelAuthenticationChallenge
credential = nil
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
print ("Server Trust")
credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
if (credential != nil) {
print ("Use credential")
disposition = .useCredential
}
else{
print ("perform default handling")
disposition = .performDefaultHandling
credential = defaultCredential
}
}
else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate {
print ("client certificate")
}
else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic {
print ("Basic authentication")
}
else{
disposition = .cancelAuthenticationChallenge
credential = nil
}
if credential != nil { challenge.sender!.use(credential!, for: challenge)}
completionHandler(disposition, credential);
}
func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
print ("URLSessionTask didReceive")
let credential = URLCredential(user: user, password: password, persistence: URLCredential.Persistence.forSession)
challenge.sender?.use(credential, for: challenge)
completionHandler(URLSession.AuthChallengeDisposition.useCredential,credential)
}
Вот выход Кодекса:
challenge NSURLAuthenticationMethodServerTrust
Server Trust
Use credential
dataTask response: <NSHTTPURLResponse: 0x610000031780> { URL: https://www.example.com/Test.nsf/0/91182C6C9EEE0414C12580A300312D1A?Opendocument } { status code: 200, headers {
"Cache-Control" = "no-cache";
"Content-Length" = 5949;
"Content-Type" = "text/html; charset=UTF-8";
Date = "Sun, 12 Feb 2017 19:14:19 GMT";
Expires = "Tue, 01 Jan 1980 06:00:00 GMT";
Server = "Lotus-Domino";
"Strict-Transport-Security" = "max-age=0";} }
Я предполагаю, что ваш код ожидает базовой аутентификации. Проверьте, какой метод проверки подлинности сервер Domino настроен для использования в рассматриваемом домене –
Кажется, проблема, характерная для IBM. Я попытался получить доступ к IBM Websphere Portal и дал аналогичные результаты, например, IBM Domino. Тем не менее, я протестировал для входа на сайт Microsoft SharePoint, это было успешно. –
Возможно, сервер IBM Domino и IBM Websphere был настроен на использование LTPA для аутентификации. Это может объяснить вашу проблему. Таким образом, вам, скорее всего, потребуется изменить метод проверки подлинности для сайта на сервере IBM Domino на основе аутентификации. –