In this post we will see how we can connect to a RESTFUL service that uses basic authentication in Swift 3.0.
Basic authentication is an authentication schema in which the client sends the user and password as base64 encoded text. Since the data is sent as unencrypted, plain text this form of authentication should be used only with HTTPS to prevent anyone from stealing our credentials. Actually, no matter which authentication method our server is using, iOS will block by default all non secure HTTP requests unless we configure the necessary exceptions for the ATS (see the article here).
Although we can perfectly do our REST request using plain Swift, it is likely that we are going to use a networking library for such tasks. Therefore I will provide the following samples:
- Basic authentication using URLRequest
- Basic authentication using Alamofire
Basic authentication using URLRequest
// credentials encoded in base64 let username = "myuser" let password = "mypasswd" let loginData = String(format: "%@:%@", username, password).data(using: String.Encoding.utf8)! let base64LoginData = loginData.base64EncodedString() // create the request let url = URL(string: "http://myurl.com")! var request = URLRequest(url: url) request.httpMethod = "GET" request.setValue("Basic \(base64LoginData)", forHTTPHeaderField: "Authorization") //making the request let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { r print("\(error)") return } if let httpStatus = response as? HTTPURLResponse { // check status code returned by the http server print("status code = \(httpStatus.statusCode)") // process result } } task.resume()
Usually an HTTP server will return a 20x if the petition was successfully processed, and a 401 error if the authentication process failed. Therefore one checks the statusCode to see what the outcome was before proceeding to process the result.
Basic authentication using Alamofire
Basic authentication in Alamofire works pretty much as any other Alamofire request, we need only add the Authentication headers.
var headers: HTTPHeaders = [ "Content-Type": "application/json" ] let user = "myuser" let password = "mypasswd" if let authorizationHeader = Request.authorizationHeader(user: user, password: password) { headers[authorizationHeader.key] = authorizationHeader.value } let url = "http://myurl.com" Alamofire.request(url, headers:headers).responseJSON{ response in switch response.resultJSON { case .success: // Do stuff case .failure(let error): print(error) }}
Actually, most of the time we can use the authenticate method provided by Alamofire for such a situation:
.authenticate(user: myuser, password: mypasswd)
But sometimes, we may find some API out there that does not get along with the .authenticate method. And in those cases we need to use the authentication headers.
I hope you find this post interesting: If that is the case, you can subscribe to my blog (click at the “follow” button at the bottom) so you can be notified of new posts.
July 19, 2017 at 2:57 pm
Does it need to be .data(using: String.Encoding.utf8)! on that string.
LikeLike
July 19, 2017 at 7:40 pm
Not exactly need. I was trying to use a character encoding in my headers that would support characters beyond ASCII, and that the server that I was using at the time would accept.
Your server may accept or even require a different encoding though.
LikeLike
February 15, 2018 at 9:28 pm
hello, I’m new at parsing JSON, and I’m using swiftyjsion, can you tell me how can I parse the data?
LikeLike
February 15, 2018 at 9:33 pm
Sorry, I’ve figured it out. Thank you for the code.
LikeLike
January 13, 2019 at 1:52 pm
Reblogged this on Tech Reblogs.
LikeLike