使用Alamofire进行基本身份验证 [英] Basic Authentication with Alamofire

查看:160
本文介绍了使用Alamofire进行基本身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Basic Auth进行身份验证时遇到问题。我正在使用符合 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) - >无效
打印(JSON响应\(响应))
完成(成功:true,错误:无)
}

它正确验证。我希望能够在符合 URLRequestConvertible 的enum中手动设置它,而不是传入 authenticate 中的凭据。



我知道它在auth挑战下使用 NSURLCredential 但我希望能够设置这是我的 URLRequestConvertible 实现:

 枚举CheckedUpAPI:URLRequestConvertible {
static let baseURLString =https:// ***
static let APIKey =***
static let APIClientName =iPad


case UpdatePatient(String,[String:AnyObject])


var method:Alamofire.Method {
切换自我{
case .UpdatePatient:
return .PATCH
}
}

var path:String {
switch self {
case .UpdatePatient(let patientID,_):
返回patients / \(pat) ientID)
}
}

// MARK:URLRequestConvertible

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


/ **
我们是没有设置任何授权标题,因为他们请求返回401
Alamofire.request上的`authenticate`函数可以解决问题

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,参数:参数).0
}
}
}


解决方案

最终找出问题所在。它最终成为URL中缺少的尾随斜杠。似乎Alamofire没有像AFNetworking那样处理它。我能够弄清楚记录请求并发现我们在实际请求中丢失了一些字节。


Experiencing an issue when authenticating with Basic Auth. I am using a standard enum that conforms to URLRequestConvertible protocol to construct my requests. The issue is that when I manually set the authorization headers in the enum like so:

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

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

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

I always get a 401 unauthorized response. However if I set the password using the authenticate callback like so:

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

It authenticates properly. I would like to be able to set it manually in the enum conforming to URLRequestConvertible instead of passing in the credentials in authenticate.

I know it's using a NSURLCredential under the hood for auth challenges but I would like to be able to set it manually.

Here is my URLRequestConvertible implementation :

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

解决方案

Ultimately figured out what the issue was. It ended up being a missing trailing forward slash in the URL. It seems Alamofire does not handle it the same way AFNetworking does. I was able to figure it out logging the requests and seeing that we were losing some bytes in the actual request.

这篇关于使用Alamofire进行基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆