Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 547
Santosh Avatar asked Oct 20 '17 15:10

Santosh


2 Answers

If you want token to be hardcoded, I guess it has to be like this:

urlRequest.httpMethod = "GET"
urlRequest.setValue("Token <Your Token>", forHTTPHeaderField: "Authorization")
like image 129
Andrey Petrov Avatar answered Sep 20 '22 01:09

Andrey Petrov


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.

like image 40
Rukshan Avatar answered Sep 19 '22 01:09

Rukshan