Search code examples
iosswiftswift2basic-authenticationalamofire

iOS - Alamofire v2 Basic Auth not working


So I'm sending a basic auth request to Bing Image Search to grab some image data, and it was working great, right until I updated to the latest version of Alamofire (1.3 -> 2.0.2), which I had to do because 1.3 wasn't even close to compatible with XCode 7.

Anyway, here is my code:

let credentials = ":\(Settings.bingApiKey)"
let plainText = credentials.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let base64 = plainText!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))

manager = Alamofire.Manager.sharedInstance
manager!.session.configuration.HTTPAdditionalHeaders = [
    "Authorization": "Basic \(base64)"
]

let url = NSURL(string: Settings.bingImageApi + "&Query=" + keyword + "&$top=15&$skip=" + String(skip))!

manager!
  .request(.POST, url, parameters: nil, encoding: .JSON)
  .responseJSON { request, response, result in
      ...

And I'm getting the error:

FAILURE: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.} The authorization type you provided is not supported. Only Basic and OAuth are supported


Solution

  • I had the same issue while moving from Alamofire 1.x to 2.x.

    One workaround I found (and that works), is to pass the headers when performing the request:

    let headers = ["Authorization": "Basic \(base64)"]
    Alamofire.request(.POST, url, parameters: nil, encoding: .JSON, headers: headers)
    

    For more information you can take a look at the documentation.