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 only be used  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 request, 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: "")!
        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

            if let httpStatus = response as? HTTPURLResponse {
           		// check status code returned by the http server
                print("status code = \(httpStatus.statusCode)")
		// process result

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 only need to 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 = ""

Alamofire.request(url, headers:headers).responseJSON{ response in

switch response.resultJSON {
case .success:
// Do stuff
case .failure(let error):

Actually, most of the time we can use the authenticate method provided by Alamofire for such 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.