0

I am trying to call a RestApi call with basic authentication. I am able to make the call succesfully, but the issue that i am facing is that if i give wrong username & password in the call, then also I am getting sucess response. I tried by making the login & pasword field as blank also, still positive response is received. I believe its a caching issue. The code that i am trying is as follows

let headers = [
            "cache-control": "no-cache"
        ]
        let login = ""
        let password = ""
        let request = NSMutableURLRequest(url: NSURL(string: urlString)! as URL,
                                          cachePolicy: .reloadIgnoringLocalAndRemoteCacheData,
                                          timeoutInterval: 10.0)
        request.httpMethod = "GET"
        request.allHTTPHeaderFields = headers

        let config = URLSessionConfiguration.default
        let loginData = String(format: "%@:%@", login, password).data(using: String.Encoding.utf8)!
        let base64EncodedCredential = loginData.base64EncodedString()
        let authString = "Basic \(base64EncodedCredential)"
        config.httpAdditionalHeaders = ["Authorization" : authString]

        let session = URLSession.shared
        let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
            if (error != nil) {
                print(error!)
            } else {
                let httpResponse = response as? HTTPURLResponse
                print(httpResponse!)
                let responseData = String(data: data!, encoding: String.Encoding.utf8)
                print(responseData!)
            }
        })
        dataTask.resume()

The call is going to an IIS server. Can someone help me to solve the issue. Thanks in advance.

Kamran
  • 14,987
  • 4
  • 33
  • 51
Jobins John
  • 1,265
  • 23
  • 45
  • 1
    Have you checked with postman? – Dharmesh Kheni Jul 11 '19 at 05:27
  • So this is not your issue. It's a backend issue. How are you supposed to authenticate on client? – Kamran Jul 11 '19 at 05:40
  • @Dharmesh With postman it is working as expected. If give right username and password, then it works fine else it gives error. – Jobins John Jul 11 '19 at 05:46
  • @Kamran Basic Authentication is handled by server, but when I am calling again and again, the previous username is getting hit on the server. We verified it by checking the server logs. – Jobins John Jul 11 '19 at 05:47
  • try adding `URLCache.shared.memoryCapacity = 0 URLCache.shared.diskCapacity = 0 URLCache.shared.removeAllCachedResponses()` in `AppDelegate`'s `didFinishLaunchingWithOptions` – Kamran Jul 11 '19 at 06:13

0 Answers0