iOS - Alamofire v2 Basic Auth not working

☆樱花仙子☆ 提交于 2019-12-12 13:08:12

问题


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


回答1:


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.




回答2:


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."




回答3:


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.



来源:https://stackoverflow.com/questions/32688546/ios-alamofire-v2-basic-auth-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!