Basic Authentication with Alamofire

拥有回忆 提交于 2019-11-30 06:38:32

In swift 3.0

Use following code -

    let user = ***
    let password = ***
    let credentialData = "\(user):\(password)".data(using: String.Encoding.utf8)!
    let base64Credentials = credentialData.base64EncodedString(options: [])
    let headers = ["Authorization": "Basic \(base64Credentials)"]

    Alamofire.request(customerURL,
                      method: .get,
                      parameters: nil,
                      encoding: URLEncoding.default,
                      headers:headers)
        .validate()
        .responseJSON { response in
            if response.result.value != nil{                    
               print(response)
            }else{

            }
    }
Alamofire.request(urlString, method: .get).authenticate(user: "username", password: "pwd").responseJSON

JUST authenticate

Pheaktra Ty

You can try this code:

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

Alamofire.manager.request(.GET, stringURL,headers: headers, parameters: params as? [String : AnyObject])
        .responseJSON { response  in
            if (response.result.error == nil){
                success(data: response.result.value)
            }else{
                fail(error: response.result.error)
            }
    }

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 provides an even easier approach than manually creating your own headers.

The relevant piece of code from "Basic Auth" section here:

  manager.request(.GET, "https://api.parse.com/1/classes/Spot/")
    .authenticate(user: username, password: password)
    .responseSpotsArray { response in
      completionHandler(response.result)
    }

Swift 4

private func getHeaders() -> [String: String] {
        let userName = "xxxx"
        let password = "xxxx"
        let credentialData = "\(userName):\(password)".data(using: .utf8)
        guard let cred = credentialData else { return ["" : ""] }
        let base64Credentials = cred.base64EncodedData(options: [])
        guard let base64Date = Data(base64Encoded: base64Credentials) else { return ["" : ""] }
        return ["Authorization": "Basic \(base64Date.base64EncodedString())"]
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!