URLSession doesn't pass 'Authorization' key in header swift 4
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.
Related videos on Youtube
Comments
-
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 over 6 years@Santosh Did you get any solution?
-
Alex Cohn over 2 years
config.httpAdditionalHeaders = [ "authorization": "token abcd"]
works for me smoothly (iOS 15).
-
-
Alex Motor over 5 yearsIt looks like correct answer. Don't modify this header in httpAdditionalHeaders.
-
Fattie over 4 yearsIt seems this is really not necessary, today anyways (fortunately!)
-
Matt Mc about 4 yearsThis is nice, but the OP seems to be asking about an auth/bearer token. However, this method only works for Basic Auth.
-
Matt Mc about 4 yearsThis is correct; setting the Auth header via
config.httpAdditionalHeaders
does not produce the intended effect. -
ettore almost 4 yearsOfficial 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 URLRequestAuthorization
header, however. -
Max MacLeod almost 4 yearsTrue. 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 over 2 years
config.httpAdditionalHeaders = [ "authorization": "token abcd"]
works for me smoothly (iOS 15).