Ryan Bobrowski
Ryan Bobrowski

Reputation: 2730

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

Upvotes: 3

Views: 1267

Answers (3)

cnoon
cnoon

Reputation: 16663

The first part of the error is due to you not receiving valid JSON in the response. You can use response, responseData or responseString to help debug.

The second part of the error is due to how you are setting the header. You cannot set an Authorization header after the session configuration has been created. You can either create your own session configuration and your own Manager, or you can pass the Authorization header in the request.

Upvotes: 0

Prabhu.Somasundaram
Prabhu.Somasundaram

Reputation: 1390

please read here http://ste.vn/2015/06/10/configuring-app-transport-security-ios-9-osx-10-11/ "App Transport Security (ATS) lets an app add a declaration to its Info.plist file that specifies the domains with which it needs secure communication. ATS prevents accidental disclosure, provides secure default behavior, and is easy to adopt. You should adopt ATS as soon as possible, regardless of whether you’re creating a new app or updating an existing one."

Upvotes: 0

Yannick Loriot
Yannick Loriot

Reputation: 7136

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.

Upvotes: 2

Related Questions