ios - 如何创建与 Alamofire 一起使用的 NTLM 身份验证 header ?

标签 ios swift alamofire ntlm-authentication

这些是请求 header :

let userName = "someUserName"
let password = "aPasswordForSomeUserName"

var headers: HTTPHeaders = [
    "Accept": "application/json",
]

if let authorizationHeader = Request.authorizationHeader(user: userName, password: password) {
    headers[authorizationHeader.key] = authorizationHeader.value
}

所以这是生成 Authorization 这样的。

Basic aC5paHFoOkulbXKhNpk43A==(为了安全,我对其进行了修改)。

但是当我在 Advance Rest Client(一个 chrome 扩展)中提出相同的请求时。我看到了这个:

Accept: application/json
Authorization: NTLM TlMMTVNTUAADAAAAGAAYAG4AAAAYABgAhgAAAAYABgBAAAAADAAMAEYAAAAcABwAUgPPPAAAAACeAAAAAYIAAEUARwBBAGgALgBzAGgAYQBoAUIOVABHAC4AUSDFGC4ARQBHAEEALgBMAEEAToD38IenExnddmNhyXz+u0cmIHEl/p8P9OWe2rePPsiRkZO1Ne6ZrWxnIxHK1CZcyTU=

注意,NTLM 和 Basic 在为我的用户名和密码生成的授权 key 中。

如何在 iOS 中执行此操作(以及可能使用 Alamofire)?

这也引出了我之前问过的这个问题。

How to make a NTML request with Alamofire 4.0?

最佳答案

我在这个 link 中增强了正确答案,并处理使用 Alamofire 发送的任何请求,而不是为每个 ViewController 添加登录名:

private var manager : SessionManager?
var username: String? = nil
var password: String? = nil

func doesHaveCredentials() -> Bool {
    self.username = Defaults[.username]
    self.password = Defaults[.password]

    guard let _ = self.username else { return false }
    guard let _ = self.password else { return false }
    return true
}

func apiManager() -> SessionManager{
    if let m = self.manager{
        return m
    }else{
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 25
        configuration.timeoutIntervalForResource = 25
        self.manager = Alamofire.SessionManager(configuration: configuration)

        let delegate: Alamofire.SessionDelegate = self.manager!.delegate
        delegate.taskDidReceiveChallengeWithCompletion = { session, task, challenge,  completionHandler in
            print("Got challenge")
            guard challenge.previousFailureCount == 0 else {
                print("too many failures")
                challenge.sender?.cancel(challenge)
                completionHandler(.cancelAuthenticationChallenge, nil)
                return
            }

            guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM else {
                print("unknown authentication method \(challenge.protectionSpace.authenticationMethod)")
                challenge.sender?.cancel(challenge)
                completionHandler(.cancelAuthenticationChallenge, nil)
                return
            }

            guard self.doesHaveCredentials() else {
                challenge.sender?.cancel(challenge)
                completionHandler(.cancelAuthenticationChallenge, nil)
                DispatchQueue.main.async {
                    print("Userdata not set")
                };
                return
            }

            let credentials = URLCredential(user: self.username!, password: self.password!, persistence: .forSession)
            challenge.sender?.use(credentials, for: challenge)
            completionHandler(.useCredential, credentials)
        }

        return self.manager!
    }
}

关于ios - 如何创建与 Alamofire 一起使用的 NTLM 身份验证 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45912952/

相关文章:

ios - 在 shouldPerformSegueWithIdentifier UIAlertController 之后未执行 Unwind Segue

ios - 如何使用操作查询发出多个 Alamofire 请求

ios - 按索引移动数组中的元素

ios - Swift - 从模型中的 API 调用返回一个 JSON 对象作为字典以在 View Controller 中使用

ios - 如何创建扩展文件并在 iOS Swift 3 的 View Controller 中调用它?

ios - SpriteKit swift : How to prevent a Crash when bodyA collisions with more than one bodyB at the same time?

iOS - Swift - 如何将按钮添加到 MKPointAnnotaton - MapKit

ios - 尝试将数据传递到另一个 View Controller 时出现 fatal error

ios - 全局变量和 Alamofire 的问题

json - Alamofire 奇怪的 JSON 前缀 - Swift 2.0