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:
That is the basic pattern for a simple request.
Send JSON with Basic Auth
The same authentication header works for POST requests too:
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:
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:passwordstring 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
Authorizationheader on aURLRequest. - Build the header from
username:password, base64-encode it, and send the request withURLSession. - 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.

