Skip to main content

Basic Authentication

This guide provides a detailed walkthrough of implementing HTTP Basic Authentication to access protected endpoints in the Sistema de Gestión de Propiedades API.

What is Basic Authentication?

HTTP Basic Authentication is a simple authentication mechanism where credentials are sent in the Authorization header as a base64-encoded string. The format is:
Authorization: Basic <base64(username:password)>
Basic Auth is standardized in RFC 7617 and widely supported by HTTP clients and libraries.

Encoding Credentials

Manual Encoding

1

Concatenate with colon

Combine your username and password with a colon separator:
admin:mysecretpass
2

Base64 encode

Encode the string using base64:
YWRtaW46bXlzZWNyZXRwYXNz
3

Add prefix

Prepend “Basic ” to the encoded string:
Basic YWRtaW46bXlzZWNyZXRwYXNz

Using Command Line

# On Linux/Mac
echo -n 'username:password' | base64

# Example output
YWRtaW46cGFzc3dvcmQ=
The -n flag is important - it prevents adding a newline character which would make the encoding invalid.

Implementation Examples

curl

JavaScript/TypeScript

// btoa is available in browsers
const username = 'admin';
const password = 'password';
const credentials = btoa(`${username}:${password}`);

const response = await fetch(
  'https://idforideas-1.jamrdev.com.ar/api/propiedades',
  {
    method: 'POST',
    headers: {
      'Authorization': `Basic ${credentials}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      pais: 'Argentina',
      ciudad: 'Buenos Aires',
      direccion: 'Av. Corrientes 1234',
      ambientes: 2,
      metros_cuadrados: 65,
      precio: 95000,
      tipo_contratacion: 'Alquiler',
      estado: 'Disponible'
    })
  }
);

if (response.ok) {
  const data = await response.json();
  console.log('Property created:', data);
} else if (response.status === 401) {
  console.error('Authentication failed');
}

Python

import requests
from requests.auth import HTTPBasicAuth

# Recommended: Let requests handle encoding
response = requests.post(
    'https://idforideas-1.jamrdev.com.ar/api/propiedades',
    auth=HTTPBasicAuth('admin', 'password'),
    json={
        'pais': 'Argentina',
        'ciudad': 'Buenos Aires',
        'direccion': 'Av. Corrientes 1234',
        'ambientes': 2,
        'metros_cuadrados': 65,
        'precio': 95000,
        'tipo_contratacion': 'Alquiler',
        'estado': 'Disponible'
    }
)

if response.status_code == 201:
    print('Property created:', response.json())
elif response.status_code == 401:
    print('Authentication failed')

Verifying Credentials

Always verify credentials before using them in your application:
curl -u admin:password \
  https://idforideas-1.jamrdev.com.ar/api/auth/verify
Success (200 OK):
{
  "authenticated": true,
  "user": "admin"
}
Failure (401 Unauthorized):
{
  "error": "Unauthorized"
}
Verify credentials during application startup or before storing them in configuration. This prevents runtime authentication failures.

Common Issues

Possible causes:
  • Extra whitespace in username or password
  • Newline character in base64 encoding (use -n flag with echo)
  • Wrong environment variables configured on server
  • Case sensitivity in credentials
Solution:
# Verify your encoding is correct
echo -n 'admin:password' | base64
# Should output: YWRtaW46cGFzc3dvcmQ=
Cause: The API has CORS enabled, but some browsers show CORS errors when auth fails.Solution: First verify credentials work with curl, then debug frontend code:
curl -v -u admin:password https://idforideas-1.jamrdev.com.ar/api/auth/verify
Cause: btoa is a browser API, not available in Node.js.Solution: Use Buffer instead:
const credentials = Buffer.from('admin:password').toString('base64');

Security Considerations

Never send credentials over HTTP. Basic Auth credentials are only base64-encoded, not encrypted. Always use HTTPS.

Best Practices

  1. Use Environment Variables
    const username = process.env.API_USERNAME;
    const password = process.env.API_PASSWORD;
    
  2. Don’t Log Credentials
    // Bad
    console.log(`Authenticating as ${username}:${password}`);
    
    // Good
    console.log(`Authenticating as ${username}`);
    
  3. Validate Input
    if (!username || !password) {
      throw new Error('Credentials not configured');
    }
    
  4. Handle Auth Errors
    if (response.status === 401) {
      // Don't retry immediately - credentials are likely wrong
      throw new Error('Authentication failed: Invalid credentials');
    }
    

Testing Authentication

Test your authentication implementation:
1

Test valid credentials

curl -u admin:correctpassword \
  https://idforideas-1.jamrdev.com.ar/api/auth/verify
# Should return 200 OK
2

Test invalid credentials

curl -u admin:wrongpassword \
  https://idforideas-1.jamrdev.com.ar/api/auth/verify
# Should return 401 Unauthorized
3

Test missing credentials

curl https://idforideas-1.jamrdev.com.ar/api/propiedades \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{"ciudad": "Test"}'
# Should return 401 Unauthorized

Next Steps

Creating Properties

Use authentication to create properties

Environment Variables

Configure credentials for deployment

Error Handling

Handle authentication errors gracefully

Verify Endpoint

API reference for credential verification

Build docs developers (and LLMs) love