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

11,921

Solution 1

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!

Solution 2

Looks like the problem is that you are modifying Authorization header using httpAdditionalHeaders which is something you should not do.

From the Doc

An NSURLSession object is designed to handle various aspects of the HTTP protocol for you. As a result, you should not modify the following headers: Authorization, Connection, Host, Proxy-Authenticate, Proxy-Authorization, WWW-Authenticate

Removing the line config.httpAdditionalHeaders = headers should fix the issue.

Share:
11,921

Related videos on Youtube

Santosh
Author by

Santosh

IOS developer, python lover. #SOreadytohelp

Updated on June 04, 2022

Comments

  • Santosh
    Santosh almost 2 years

    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.

    • Rounak
      Rounak over 6 years
      @Santosh Did you get any solution?
    • Alex Cohn
      Alex Cohn over 2 years
      config.httpAdditionalHeaders = [ "authorization": "token abcd"] works for me smoothly (iOS 15).
  • Alex Motor
    Alex Motor over 5 years
    It looks like correct answer. Don't modify this header in httpAdditionalHeaders.
  • Fattie
    Fattie over 4 years
    It seems this is really not necessary, today anyways (fortunately!)
  • Matt Mc
    Matt Mc about 4 years
    This is nice, but the OP seems to be asking about an auth/bearer token. However, this method only works for Basic Auth.
  • Matt Mc
    Matt Mc about 4 years
    This is correct; setting the Auth header via config.httpAdditionalHeaders does not produce the intended effect.
  • ettore
    ettore almost 4 years
    Official docs for URLRequest point to this page, which mentions to avoid modifying certain headers such as Authorization. This thread on Apple forums provide an example using delegates callback for handling username/password basic and digest authentication. For Bearer token authentication, this other thread suggests that there is no client-side alternative to modifying the URLRequest Authorization header, however.
  • Max MacLeod
    Max MacLeod almost 4 years
    True. Worth noting however that not all REST API services supply an authentication challenge. In that case, the recommended Apple delegate approach will fail. Always check the REST API docs first.
  • Alex Cohn
    Alex Cohn over 2 years
    config.httpAdditionalHeaders = [ "authorization": "token abcd"] works for me smoothly (iOS 15).