Sending an HTTP request with basic authentication

Sending an HTTP request with basic authentication

How to:

Let’s get our hands dirty with some code. We’ll use curl, a common command-line tool. Replace username:password with your credentials and with your target URL.

curl -u username:password

Or encode your credentials in base64 beforehand and use them like so:

# Encode credentials
credentials=$(echo -n username:password | base64)

# Sending the request
curl -H "Authorization: Basic $credentials"

Sample output for a successful request might look like this:

  "data": "Some restricted info",
  "message": "Access granted"

Deep Dive

Historically, basic authentication has been part of HTTP since the early days, but it’s not without flaws – mainly its vulnerability if not used over a secure channel like HTTPS.

Alternatives include OAuth, which is more secure and provides finer-grained control over what’s accessed. Digest authentication is another, sending hashed credentials rather than plain text.

As for the mechanics, when you send basic auth credentials, they’re included in the HTTP header encoded in Base64. It’s not encryption, so if you’re not using HTTPS, anyone who intercepts the request can decode it easily. Using HTTPS secures the transmission, encrypting everything between client and server.

See Also