URLSession doesn't pass 'Authorization' key in header swift 4

Santosh picture Santosh · Oct 20, 2017 · Viewed 9.3k times · Source

I am trying to pass authorization key in header of a URLRequest. But at the server end the key is not received. The same API when called from postman working fine. Any other key in the header is working fine, even authorizations key is visible at server end.

Here is my code:

let headers = [
    "authorization": "token abcd"
]

var request = URLRequest.init(url: NSURL(string:
    "http://127.0.0.1:7000/api/channels?filter=contributed")! as URL)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = headers
let session = URLSession.init(configuration: config)

let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
    if (error != nil) {
        print(error ?? "")
    } else {
        let httpResponse = response as? HTTPURLResponse
        print(httpResponse ?? "")
    }
})

As you can see, I tried to set the token in both session config and request but none is working.

Answer

William T. Mallard picture William T. Mallard · Mar 20, 2018

This seems to be working:

// Set the security header
private var credentials: String {
    return "\(participantId):\(password)"
}

private var basicAuthHeader: String {
    return "Basic \(credentials)"
}

func getSettings(participantId: Int, password: String) -> Bool {

    self.participantId = participantId
    self.password = password

    let path = "/settings/\(participantId)"
    guard let url = URL(string: "\(BASE_URL)\(path)") else {
        Log.e("Invalid URL string, could not convert to URL")
        return false
    }

    var urlRequest = URLRequest(url: url)
    urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
    urlRequest.setValue(basicAuthHeader, forHTTPHeaderField: "Authorization")
    urlRequest.setValue(APP_FILE_NAME, forHTTPHeaderField: "User-Agent")

    // This is a synchronous wrapper extension around URLSession.dataTask()
    let (data, response, error) = URLSession.shared.synchronousDataTask(with: urlRequest)
    // Process the result...
}

Note: code written by my coworker. Thanks John!