如何使用Alamofire 4.0发出NTML请求?

时间:2017-08-28 05:42:26

标签: ios swift alamofire ntlm-authentication

这些是请求标头:

    let headers: HTTPHeaders = [
        "Accept": "application/json",
        "username": "someUserName",
        "password": "aPasswordForSomeUserName"
    ]

当使用下面的代码发出请求时,它会给我“最后的垃圾”。然而,当我在线检查JSON解析器的响应时。这是一个有效的JSON。

Alamofire.request("http://myserver/list.svc/random", headers: headers).responseJSON { response in
    print(response)
}

我也尝试过这样的请求

Alamofire.request("http://myserver/list.svc/random", headers: headers).responseString { response in
    print(response)
}

我在控制台收到此消息:“401 UNAUTHORIZED”

我做错了什么?我相信,当使用responseJSON完成块时,它并不是在抱怨Unauthorization,而是在抱怨糟糕的JSON(或一些垃圾)。

P.S。相同的请求适用于Advance Rest Client(Chrome扩展程序)以及chrome浏览器。

2 个答案:

答案 0 :(得分:2)

我不知道这对你有多重要,但我已经找到了一个可行的解决方案,我将发布以供将来参考。

所以,我有两个问题。第一个是当重定向时,Authorization标头落在请求中。第二个是来自服务器的NTLM挑战未被处理。以下代码应该是非常自我解释我希望:)它假设您将用户名和密码存储在变量名称中。

    let credentialData = "\(username):\(password)".data(using: String.Encoding.utf8)!
    let base64Credentials = credentialData.base64EncodedString(options: [])
    request.addValue("Basic \(base64Credentials)", forHTTPHeaderField: "Authorization")

    let manager = Alamofire.SessionManager.default
    let delegate: Alamofire.SessionDelegate = manager.delegate

    // This bit will re-add the auth headers for the redirected request
    delegate.taskWillPerformHTTPRedirection = { session, task, response, request in
        var redirectedRequest = request

        if let originalRequest = task.originalRequest, let redirectheaders = originalRequest.allHTTPHeaderFields {
            if let authorizationHeaderValue = redirectheaders["Authorization"] {
                redirectedRequest.setValue(authorizationHeaderValue, forHTTPHeaderField: "Authorization")
            }
            if let contentTypeHeaderValue = redirectheaders["Content-Type"] {
                redirectedRequest.setValue(contentTypeHeaderValue, forHTTPHeaderField: "Content-Type")
            }
        }

        return redirectedRequest
    }

    // This bit looks at challenges received and applies the correct credentials
    delegate.taskDidReceiveChallenge = { session, task, challenge in
        var disposition: URLSession.AuthChallengeDisposition = .useCredential
        var credential: URLCredential = URLCredential()

        if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM) {
            disposition = URLSession.AuthChallengeDisposition.useCredential
            credential = URLCredential(user: username, password: password, persistence: URLCredential.Persistence.forSession)
        }

        if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
            disposition = URLSession.AuthChallengeDisposition.useCredential
            credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
        }

        return(disposition, credential)
    }

    manager.request(request).responseData { (response) in
        // Handle response accordingly
    }

希望这有助于某人。

答案 1 :(得分:0)

Swift4.2

Alamofire内置了NTLM身份验证支持。 您可以发出这样的请求

        let user = "YOUR_USER_NAME OR EMAIL"
        let password = "YOUR_PASSWORD"
        let url = "YOUR_API_URL"
        let credential = URLCredential(user: user, password: password, persistence: .forSession)
        //These headers are optional based on your api and your server.
        //There were required for me
        let headers = ["Accept": "application/json;odata=verbose",
                           "Content-type": "application/json;odata=verbose"]
        Alamofire.request(url, method: .get, headers: headers).authenticate(usingCredential: credential).responseJSON {
                (response) in
                switch response.result {
                case .success:
                    if let value = response.result.value {
                        print("The server response is: ", value)
                    }else{
                        print("There is error in the server response")
                    }
                case .failure (let error):
                    print("The NTLM request error is: ", error.localizedDescription)
                }

            }