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
Basic Authentication in Swift is straightforward to implement, but it must be done carefully to avoid insecure credential handling. The core idea is to send an Authorization header with a Base64-encoded username:password string over HTTPS. This guide shows practical request patterns, error handling, and security improvements for production apps.
Core Topic Sections
Understand Basic Auth in practice
Basic Auth sends credentials with each request. Base64 encoding is not encryption, so transport security is mandatory.
Required rule:
- Use HTTPS only.
- Never send Basic Auth over plain HTTP.
If the server supports token-based flows, Basic Auth is often used only once to exchange for a short-lived token.
Build the authorization header in Swift
This helper keeps header generation isolated and testable.
Make a GET request with URLSession
This pattern is compact and production-friendly for many API clients.
Make a POST request with JSON body
For modern Swift code, async and await gives cleaner flow than callback nesting.
Avoid hardcoded credentials
Never keep production credentials in source code. Safer options:
- Store user secrets in Keychain.
- Use secure backend-provided tokens where possible.
- Inject credentials via secure config for debug builds only.
Even in internal apps, source-level secrets are frequently leaked through logs or screenshots.
Handle auth failures and retries correctly
On 401 responses:
- Do not retry indefinitely with same credentials.
- Clear invalid cached credential state.
- Prompt re-authentication or refresh token flow.
Also log status code and request identifier, not raw credential strings.
Use URLCredential when challenge flow is required
Some servers challenge first and expect credential response. Delegate-based handling can be useful.
Header-based auth is still more common for API-style Basic Auth, but challenge handling matters for some legacy endpoints.
Testing strategy
Validate these scenarios:
- Success with valid credentials.
- Unauthorized response with invalid credentials.
- Network timeout handling.
- JSON decode failure handling.
A small mocked API test harness prevents regressions in networking layers.
Common Pitfalls
- Sending Basic Auth over non-HTTPS endpoints.
- Treating Base64 as encryption and exposing credentials carelessly.
- Hardcoding credentials in source code and committing secrets.
- Retrying failed auth requests without handling
401correctly. - Logging full request headers that include
Authorizationvalues.
Summary
- Basic Auth in Swift is implemented through the
Authorizationheader. - Use
URLSessionwith async and await for clean request code. - Enforce HTTPS and secure credential storage from the start.
- Add explicit handling for
401, timeouts, and parse failures. - Prefer token exchange flows when backend supports stronger auth models.

