Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Authentication with Alamofire

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
        }
    }
}
like image 260
Walter Martin Vargas-Pena Avatar asked Feb 18 '16 22:02

Walter Martin Vargas-Pena


People also ask

What is the use of Alamofire?

Alamofire is a networking library written in Swift. You use it to make HTTP(S) requests on iOS, macOS and other Apple platforms. For example, to post data to a web-based REST API or to download an image from a webserver. Alamofire has a convenient API built on top of URLSession (“URL Loading System”).


3 Answers

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{

            }
    }
like image 67
be.with.veeresh Avatar answered Oct 16 '22 07:10

be.with.veeresh


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

JUST authenticate

like image 39
Badre Avatar answered Oct 16 '22 09:10

Badre


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)
            }
    }
like image 21
Pheaktra Ty Avatar answered Oct 16 '22 08:10

Pheaktra Ty