这些是请求标头:
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都是为我的用户名和密码生成的授权密钥。
如何在iOS(以及可能的Alamofire)中执行此操作?
这也引出了我之前提出的这个问题。
答案 0 :(得分: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!
}
}