gpt4 book ai didi

ios - 使用 Alamofire 进行基本身份验证

转载 作者:IT王子 更新时间:2023-10-29 05:14:55 24 4
gpt4 key购买 nike

使用基本身份验证进行身份验证时遇到问题。我正在使用符合 URLRequestConvertible 协议(protocol)的标准枚举来构造我的请求。问题是当我像这样在枚举中手动设置授权 header 时:

    let user = ***
let password = ***

let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
let base64Credentials = credentialData.base64EncodedStringWithOptions([])

mutableURLRequest.setValue("Basic \(base64Credentials)", forHTTPHeaderField: "Authorization")

我总是收到 401 未经授权的响应。 但是如果我使用 authenticate 回调设置密码,如下所示:

    Alamofire.request(request)
.authenticate(user: "USERNAME_HERE", password: "PASSWORD_HERE")
.responseJSON { (response) -> Void in
print("JSON response \(response)")
completion(success: true, error: nil)
}

它正确地进行了身份验证。我希望能够在符合 URLRequestConvertible 的枚举中手动设置它,而不是在 authenticate 中传递凭据。

我知道它在后台使用 NSURLCredential 进行身份验证挑战,但我希望能够手动设置它。

这是我的 URLRequestConvertible 实现:

enum CheckedUpAPI: URLRequestConvertible {
static let baseURLString = "https://***"
static let APIKey = "***"
static let APIClientName = "iPad"


case UpdatePatient(String, [String: AnyObject])


var method: Alamofire.Method {
switch self {
case .UpdatePatient:
return .PATCH
}
}

var path: String {
switch self {
case .UpdatePatient(let patientID, _):
return "patients/\(patientID)"
}
}

// MARK: URLRequestConvertible

var URLRequest: NSMutableURLRequest {
let URL = NSURL(string: CheckedUpAPI.baseURLString)!
let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path))
mutableURLRequest.HTTPMethod = method.rawValue


/**
We are not setting any authorization headers since they requests return 401
the `authenticate` function on Alamofire.request does the trick

let user = "easy@test.com"
let password = "test"

let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
let base64Credentials = credentialData.base64EncodedStringWithOptions([])

mutableURLRequest.setValue("Basic \(base64Credentials)", forHTTPHeaderField: "Authorization")
*/
mutableURLRequest.setValue(CheckedUpAPI.APIKey, forHTTPHeaderField: "API-Key")

switch self {
case .UpdatePatient(_, let parameters):
return Alamofire.ParameterEncoding.JSON.encode(mutableURLRequest, parameters: parameters).0
}
}
}

最佳答案

在 swift 3.0 中

使用下面的代码-

    let user = ***
let password = ***
let credentialData = "\(user):\(password)".data(using: String.Encoding.utf8)!
let base64Credentials = credentialData.base64EncodedString(options: [])
let headers = ["Authorization": "Basic \(base64Credentials)"]

Alamofire.request(customerURL,
method: .get,
parameters: nil,
encoding: URLEncoding.default,
headers:headers)
.validate()
.responseJSON { response in
if response.result.value != nil{
print(response)
}else{

}
}

关于ios - 使用 Alamofire 进行基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35494157/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com