一尘不染

使用Alamofire的基本身份验证

swift

使用基本身份验证进行身份验证时遇到问题。我正在使用符合URLRequestConvertible协议的标准枚举来构造我的请求。问题是,当我在枚举中手动设置授权标头时,如下所示:

    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
        }
    }
}

阅读 448

收藏
2020-07-07

共1个答案

一尘不染

最终弄清楚了问题所在。它最终成为URL中缺少的尾随正斜杠。看来Alamofire不能像AFNetworking那样处理它。我能够弄清楚记录请求并看到我们在实际请求中丢失了一些字节。

2020-07-07