Basic authentication relies on a username and password encoded into the Authorization header of a HTTP request. Servers validate these credentials and grant access if they are correct, providing a simple authentication method for services without token-based schemes.
When integrated with cURL, credentials are passed directly, and cURL encodes them into the appropriate Authorization header. The server checks these credentials and, if valid, returns the requested content. Keeping credentials secure prevents exposure in logs and histories.
In environments that handle sensitive data, storing credentials in files or environment variables reduces risk. Proper credential management, combined with careful handling in cURL, ensures basic authentication remains safe and effective.
Steps to use basic authentication in cURL:
- Open a terminal.
- Specify the username:password combination with --user.
$ curl --user username:password "http://www.example.com/" { "data": "sample response" }
The --user option encodes credentials into the Authorization: Basic header.
- Use --verbose to inspect the encoded credentials.
$ curl --user username:password "http://www.example.com/" --verbose > GET / HTTP/1.1 > Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
--verbose displays the base64-encoded credentials in the request.
- Store credentials in a separate file.
$ echo "username:password" > .credentials
Ensure appropriate file permissions to prevent unauthorized access.
- Load credentials from the file using command substitution.
$ curl --user "$(cat .credentials)" "http://www.example.com/" { "data": "sample response" }
Loading credentials from a file keeps them out of shell histories.
- Remove or overwrite the credentials file if no longer needed.
$ shred -u .credentials
Always secure or remove sensitive data to prevent unauthorized access.
Mohd Shakir Zakaria is an experienced cloud architect with a strong development and open-source advocacy background. He boasts multiple certifications in AWS, Red Hat, VMware, ITIL, and Linux, underscoring his expertise in cloud architecture and system administration.
Comment anonymously. Login not required.