Alamofire: Basic Auth user credentials not being passed with request

I’m trying to use the example from NSHipster to do Basic Auth. I form my request like so:

        Alamofire.request(.POST, "https://my.url.com/api/v1/auth")
            .authenticate(HTTPBasic: email, password: password)
            .responseJSON {(request, response, JSON, error) in
                println(request)
                println(response)
                println(JSON)
                println(error)
        }

Email and password are just strings here. I am getting a response suggesting that the credentials aren’t attached.

Optional(<NSHTTPURLResponse: 0x7fb699783080> { URL: https://my.url.com/api/v1/auth } { status code: 401, headers {
    Allow = "POST, OPTIONS";
    Connection = "keep-alive";
    "Content-Language" = "en-us";
    "Content-Length" = 59;
    "Content-Type" = "application/json";
    Date = "Mon, 11 Aug 2014 13:34:36 GMT";
    Server = "gunicorn/17.5";
    Vary = "Accept, Accept-Language";
    "Www-Authenticate" = "Basic realm=\"api\"";
    "X-Frame-Options" = SAMEORIGIN;
} })
Optional({
    detail = "Authentication credentials were not provided.";
})

When I make the same request while using AFNetworking, I get a successful 200 response.

        let manager = AFHTTPRequestOperationManager()
        manager.requestSerializer.clearAuthorizationHeader()
        manager.requestSerializer.setAuthorizationHeaderFieldWithUsername(emailTextField.text, password:passwordTextField.text)
        manager.POST(
            "https://my.url.com/api/v1/auth",
            parameters: nil,
            success: { (operation: AFHTTPRequestOperation!,
                responseObject: AnyObject!) in
                println("JSON: " + responseObject.description)
            },
            failure: { (operation: AFHTTPRequestOperation!,
                error: NSError!) in
                println("Error: " + error.localizedDescription)
        })

If I’m making a mistake in my request with AlamoFire, would you mind pointing it out?

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Comments: 19 (5 by maintainers)

Most upvoted comments

Same thing. 👊 :
Quite confusing after AFNetworking (since I worried, when found, that authenticate called after request), but it’s quite unclear for first time usage.

And update for @loopj code in favor of Swift 1.2:

let plainString = "\(user):\(password)" as NSString
let plainData = plainString.dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))

Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["Authorization": "Basic " + base64String!]

For future travelers, if you’d like to pre-authorize:

let plainString = "\(user):\(password)" as NSString
let plainData = plainString.dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)

Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["Authorization": "Basic " + base64String!]

Alamofire.request(.GET, "http://example.com")
    .response {(request, response, _, error) in
        println(response)
    }

This caught me too. Thank you for explaining! Code below to hopefully save someone else time.

let plainString = "username:password" as NSString
let plainData = plainString.dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
Alamofire.Manager.sharedInstance.defaultHeaders["Authorization"] = "Basic " + base64String!

Encoding code adopted from http://ios-blog.co.uk/tutorials/quick-tips/base64-decoding-in-ios-7-objective-c-and-ios8-swift/

As an update to @loopj @skywinder implementation, with AlamoFire > 4.0.0, you can alternatively use the static func authorizationHeader in Request.swift, which conveniently does the encoding for you. Something like:

static func getRequestHttpHeaders() -> HTTPHeaders {
    let authTuple: (key: String, value: String)? = Request.authorizationHeader(user: user, password: password)
    return [authTuple?.key : authTuple?.value, $(OTHER_HEADERS)]
}

@brow Thanks for the heads up. Can someone please comment on why this is not recommended?