0

I try to make an http request to a server protected by basic http authentification in swift for an app targeting iOS 10.3.

I try to had the authentification header to my request :

var request = URLRequest(url: URL(string: "https://my.webservice.url")!)
request.setValue("Basic my_auth_header", forHTTPHeaderField: "Authorization")
NSLog("headers = %@", request.allHTTPHeaderFields!)

let task = URLSession.shared.dataTask(with: mutableRequest, completionHandler: {data, response, error -> () in
    do {
        let httpResponse = response as! HTTPURLResponse
        NSLog("response code %i", httpResponse.statusCode)
    }
})

In the log, i can see my header before the request,but i always get a 401 status code.

In the documentation about url request i read that some header are reserved and should not be modify, these headers include Authorization.

I try to implement URLSessionDelegate in particular the function urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void). But i do not have any clue how to create a credential for basic http authentification.

So my question is, how to handle basic http authentification in swift ?

Wukerplank
  • 4,156
  • 2
  • 28
  • 45
sonic
  • 1,894
  • 1
  • 18
  • 22
  • The accepted answer on this question use NSURLConnection, and i try to use NSURLSession. Also, i underdtand that the documentation state that you should not use the authorization header. – sonic Oct 10 '17 at 07:04
  • So, why do you alter the auth header? You already found the appropriate callback for the `URLSessionDelegate`, all you have to do is to provide the credentials to the challenger: `if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic{ print("send credential HTTP Basic") let defaultCredentials: URLCredential = URLCredential(user: "username", password: "password", persistence:URLCredential.Persistence.forSession) challenge.sender!.use(defaultCredentials, for: challenge) }` – Wukerplank Oct 10 '17 at 09:00

0 Answers0