2

这些是请求标头:

    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(或一些垃圾)。

PS 同样的请求适用于 Advance Rest Client(一个 chrome 扩展)和 chrome 浏览器。

4

2 回答 2

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
    }

希望这可以帮助某人。

于 2018-06-11T09:35:50.947 回答
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)
                }

            }
于 2019-10-09T21:01:26.807 回答