Swift
HTTP request
basic authentication
iOS development
Swift programming

How to make an HTTP request basic auth in Swift

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

To make an HTTP request with Basic Authentication in Swift, create a URLRequest, build the Authorization header from username:password, base64-encode that string, and send the request with URLSession.

The critical detail is that Basic Auth is just an HTTP header format. It is not encryption. The credentials should therefore be sent only over HTTPS, and if the app stores them at all, they should be handled with care, typically in the Keychain.

Build the Basic Auth Header

The header format is:

  • 'Authorization: Basic <base64(username:password)>'

Here is a complete GET request example:

swift
1import Foundation
2
3let username = "demo"
4let password = "secret"
5let loginString = "\(username):\(password)"
6let loginData = Data(loginString.utf8)
7let base64Login = loginData.base64EncodedString()
8
9let url = URL(string: "https://example.com/api/profile")!
10var request = URLRequest(url: url)
11request.httpMethod = "GET"
12request.setValue("Basic \(base64Login)", forHTTPHeaderField: "Authorization")
13
14let task = URLSession.shared.dataTask(with: request) { data, response, error in
15    if let error = error {
16        print("Request failed:", error)
17        return
18    }
19
20    if let httpResponse = response as? HTTPURLResponse {
21        print("Status code:", httpResponse.statusCode)
22    }
23
24    if let data = data, let text = String(data: data, encoding: .utf8) {
25        print(text)
26    }
27}
28
29task.resume()

That is the basic pattern for a simple request.

Send JSON with Basic Auth

The same authentication header works for POST requests too:

swift
1import Foundation
2
3let url = URL(string: "https://example.com/api/items")!
4var request = URLRequest(url: url)
5request.httpMethod = "POST"
6request.setValue("application/json", forHTTPHeaderField: "Content-Type")
7request.setValue("Basic \(base64Login)", forHTTPHeaderField: "Authorization")
8
9let body = ["name": "widget", "count": 3]
10request.httpBody = try JSONSerialization.data(withJSONObject: body)
11
12URLSession.shared.dataTask(with: request) { data, response, error in
13    if let error = error {
14        print(error)
15        return
16    }
17
18    if let response = response as? HTTPURLResponse {
19        print(response.statusCode)
20    }
21}.resume()

The authentication mechanism does not change just because the HTTP method changes.

Handle Status Codes Explicitly

Basic Auth failures usually appear as HTTP status 401 Unauthorized or sometimes 403 Forbidden depending on the server. So do not assume that the request succeeded just because the completion handler ran.

A practical pattern is to check:

  • network error
  • HTTP status code
  • response body or decoded payload

That makes authentication issues much easier to diagnose.

Create a Reusable Helper

If several endpoints use the same credentials, wrap header creation in a helper so every request is built consistently:

swift
1func makeBasicAuthHeader(username: String, password: String) -> String {
2    let login = "\(username):\(password)"
3    let data = Data(login.utf8)
4    return "Basic \(data.base64EncodedString())"
5}

This is also a reminder that most APIs expect the header to be sent preemptively. You usually do not wait for an authentication challenge first; you attach the Authorization header on the initial request.

Use HTTPS and Secure Storage

Basic Auth sends a reversible credential header on every request. HTTPS protects it in transit, but it is still a sensitive secret and should not be hard-coded in a production app.

If the app must persist credentials, store them in the Keychain rather than in plain text or UserDefaults. In many modern systems, token-based authentication is preferred over Basic Auth for mobile apps, but the HTTP header pattern is still common for internal tools and some APIs.

Common Pitfalls

  • Forgetting to base64-encode the exact username:password string before adding it to the header.
  • Sending Basic Auth over plain HTTP instead of HTTPS.
  • Hard-coding credentials directly into the app source.
  • Ignoring the HTTP status code and assuming a completed request means successful authentication.

Summary

  • Basic Auth in Swift is just an Authorization header on a URLRequest.
  • Build the header from username:password, base64-encode it, and send the request with URLSession.
  • The same pattern works for GET, POST, and other HTTP methods.
  • Always use HTTPS because Basic Auth is not secure by itself.
  • Treat the credentials as secrets and store them carefully if persistence is required.

Course illustration
Course illustration

All Rights Reserved.