Basic Authentication with Alamofire
Asked Answered
L

6

25

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 = "[email protected]"
        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
        }
    }
}
Lai answered 18/2, 2016 at 22:57 Comment(3)
Please share how you're making your request using your mutableURLRequest header using AlamofireTruett
@VictorSigler Done. The manual setting of the headers is commented out since it never worked. but thats what i tried with and it would not work when using the authenticate function from AlamofireLai
@VictorSigler any idea?Lai
L
1

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.

Lai answered 18/3, 2016 at 14:17 Comment(0)
M
35

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{

            }
    }
Mooring answered 16/10, 2016 at 18:57 Comment(0)
A
27
Alamofire.request(urlString, method: .get).authenticate(user: "username", password: "pwd").responseJSON

JUST authenticate

Arran answered 14/7, 2017 at 10:29 Comment(1)
This answer is too easy :DCruce
W
21

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)
            }
    }
Weinshienk answered 19/2, 2016 at 10:5 Comment(2)
Thanks for your response. This would work but then it will litter my code with this all over the place. What i;m trying to get working keeping it separating all the network stuff in a URLRequestConvertible implementationLai
Please let me know In above code where I have to add my certificate path ? In my case my certificate belongs to NSBundle folder..? please help me If you know.Shofar
C
8

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())"]
    }
Calamander answered 8/10, 2018 at 15:1 Comment(1)
iOS may not send the Authorization header when you set it directly. See developer.apple.com/documentation/foundation/nsurlrequestInvasion
H
4

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)
    }
Hilary answered 10/6, 2017 at 3:14 Comment(0)
L
1

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.

Lai answered 18/3, 2016 at 14:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.