Maysam
Maysam

Reputation: 7367

Authorization header using Alamofire

I'm working with an API which puts an authorization key in the header, it works fine in Postman:

Postman snippet

And it's my code:

let url = Requests.listCities(withLanguage: .en)
        let headers: HTTPHeaders = [ "Authorization": "pmJAdo5N26WW74kCEy6RRvIdCScFCbAtKc2o0FNy"]
        Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers)
            .validate(contentType: [MIMEType.JSON])
            .responseJSON {response in
                completion(response)
        }

The response is:

SUCCESS: {
    error = Unauthorized;
    status = failed;
}

Am I doing it wrong or is the Authorization omitted during the request?

This is the request debug:

$ curl -v \
    -H "Accept-Language: en;q=1.0, ar-US;q=0.9" \
    -H "Authorization: pmJAdo5N26WW74kCEy6RRvIdCScFCbAtKc2o0FNy" \
    -H "User-Agent: skinup/1.0 (appname; build:1; iOS 10.3.1) Alamofire/4.5.0" \
    -H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" 

Upvotes: 1

Views: 4374

Answers (1)

Alfredo Luco G
Alfredo Luco G

Reputation: 974

You can set the Alamofire's headers into an URLRequest. So you can do this:

    var urlRequest = URLRequest(url: URL(string: "your URL")!)
    urlRequest.httpMethod = HTTPMethod.get.rawValue
    urlRequest = try! URLEncoding.default.encode(urlRequest, with: nil)
    urlRequest.setValue("pmJAdo5N26WW74kCEy6RRvIdCScFCbAtKc2o0FNy", forHTTPHeaderField: "Authorization")

    Alamofire.request(urlRequest).responseJSON(completionHandler: {
        response in

        //code below
        completion(response)
    })

Maybe It would solve your problem ;)

Upvotes: 2

Related Questions