Proxy Authentication Methods Explained

Choosing the right authentication method for your proxy setup impacts security, scalability, and ease of deployment. This guide compares the three main authentication approaches and shows you how to implement each.

Authentication Methods Overview

1. Username/Password Authentication

How it works: Include credentials in the proxy URL or send them via Proxy-Authorization header.

# Format 1: URL-embedded credentials
proxy_url = "http://username:[email protected]:8080"

# Format 2: Explicit header (less common)
headers = {
    'Proxy-Authorization': 'Basic ' + base64.b64encode(b'username:password').decode()
}

Pros:

  • ✅ Works everywhere (broad client support)
  • ✅ Easy to test manually
  • ✅ No infrastructure setup required
  • ✅ Can rotate per-user or per-project

Cons:

  • ❌ Credentials in logs/URLs can leak
  • ❌ Harder to rotate at scale
  • ❌ Less secure over non-HTTPS connections

Best for: Small teams, development environments, quick testing


2. IP Whitelist Authentication

How it works: Proxy server only accepts connections from pre-approved IP addresses.

# No credentials needed in code
proxy_url = "http://proxy.hbridg.com:8080"

# Your server IP must be whitelisted first
response = requests.get(target_url, proxies={'http': proxy_url})

Pros:

  • ✅ No credentials to manage or leak
  • ✅ Faster (no auth overhead per request)
  • ✅ Simpler code
  • ✅ Better security when static IPs available

Cons:

  • ❌ Requires static IP infrastructure
  • ❌ Not suitable for dynamic/residential client IPs
  • ❌ Harder to debug ("why isn't this working?")
  • ❌ Cloud auto-scaling complicates setup

Best for: Production servers with static IPs, datacenter deployments, high-volume scraping


3. API Token Authentication

How it works: Send a bearer token via custom header or query parameter.

# Method 1: Custom header
headers = {
    'X-Proxy-Auth': 'your-api-token-here'
}
proxy_url = "http://proxy.hbridg.com:8080"

# Method 2: Query parameter
proxy_url = "http://proxy.hbridg.com:8080?token=your-api-token-here"

response = requests.get(target_url, 
                       proxies={'http': proxy_url},
                       headers=headers)

Pros:

  • ✅ Easy to rotate (generate new tokens)
  • ✅ Granular permissions (different tokens for different scopes)
  • ✅ Audit trail (track usage per token)
  • ✅ Works from any IP
  • ✅ Can set expiration

Cons:

  • ❌ Not all clients support custom headers
  • ❌ Query-param tokens visible in logs
  • ❌ Requires token management system

Best for: API-first architectures, CI/CD pipelines, multi-tenant SaaS


Implementation Guide

Setting Up Username/Password

HBridg Console:

  1. Go to Settings → Credentials
  2. Create a new credential pair
  3. Set optional IP restrictions
  4. Copy the generated proxy URL

Code example (Python):

import requests

PROXY_URL = "http://user_abc123:[email protected]:8080"

session = requests.Session()
session.proxies = {
    'http': PROXY_URL,
    'https': PROXY_URL
}

# All requests now use authenticated proxy
response = session.get('https://httpbin.org/ip')
print(response.json())

Security tips:

  • Store credentials in environment variables
  • Use different credentials per environment (dev/staging/prod)
  • Rotate credentials quarterly
  • Monitor for unusual traffic patterns

Setting Up IP Whitelist

HBridg Console:

  1. Go to Settings → IP Whitelist
  2. Add your server's public IP(s)
  3. Save and wait 2-3 minutes for propagation

Finding your server IP:

# On your server
curl https://api.ipify.org

Code example (Node.js):

const axios = require('axios');
const HttpsProxyAgent = require('https-proxy-agent');

const proxyAgent = new HttpsProxyAgent('http://proxy.hbridg.com:8080');

axios.get('https://httpbin.org/ip', {
  httpsAgent: proxyAgent
}).then(response => {
  console.log(response.data);
});

Common issues:

  • "Proxy authentication required" → Your IP isn't whitelisted yet
  • NAT/firewall hiding real IP → Check what IP the proxy sees: curl -x http://proxy.hbridg.com:8080 https://httpbin.org/ip
  • Cloud load balancer IPs → Whitelist the LB's egress IPs, not backend instances

Setting Up API Tokens

HBridg Console:

  1. Go to Settings → API Tokens
  2. Click "Generate New Token"
  3. Set name, expiration, rate limits
  4. Copy token (shown once)

Code example (Go):

package main

import (
    "net/http"
    "net/url"
)

func main() {
    proxyURL, _ := url.Parse("http://proxy.hbridg.com:8080")
    
    client := &http.Client{
        Transport: &http.Transport{
            Proxy: http.ProxyURL(proxyURL),
        },
    }
    
    req, _ := http.NewRequest("GET", "https://httpbin.org/ip", nil)
    req.Header.Set("X-Proxy-Auth", "hbridg_token_abc123xyz")
    
    resp, _ := client.Do(req)
    defer resp.Body.Close()
    
    // Handle response
}

Token rotation strategy:

import os
from datetime import datetime, timedelta

class TokenManager:
    def __init__(self):
        self.current_token = os.getenv('HBRIDG_TOKEN')
        self.rotation_date = datetime.now() + timedelta(days=30)
    
    def get_token(self):
        if datetime.now() > self.rotation_date:
            self.rotate_token()
        return self.current_token
    
    def rotate_token(self):
        # 1. Generate new token in console
        # 2. Update environment variable
        # 3. Keep old token valid for 24h grace period
        # 4. Revoke old token after grace period
        pass

Comparison Matrix

FeatureUsername/PasswordIP WhitelistAPI Token
Setup complexityLowMediumMedium
Client supportUniversalUniversalVariable
Credential leakage riskMediumNoneLow
Rotation easeHardN/AEasy
Suitable for CI/CD✅❌✅
Suitable for mobile clients✅❌✅
Granular permissions❌❌✅
Audit trailBasicIP logs onlyDetailed
Performance overheadLowNoneLow

Hybrid Approaches

Username/Password + IP Whitelist

Best of both worlds for production:

# Code uses credentials
PROXY_URL = "http://prod_user:[email protected]:8080"

# BUT proxy also enforces IP whitelist
# → Even if credentials leak, attacker needs your IP

Recommended for: Production environments with static infrastructure

API Token with IP Restriction

# Token is scoped to specific IPs
headers = {'X-Proxy-Auth': 'token_restricted_to_cidr_block'}

Recommended for: High-security scenarios, financial/healthcare data


Security Checklist

  • Never hardcode credentials in source code
  • Use environment variables or secrets manager
  • Enable HTTPS endpoints where possible
  • Rotate credentials every 30-90 days
  • Monitor for unusual traffic patterns
  • Set rate limits per credential/IP
  • Log authentication failures
  • Revoke unused credentials immediately
  • Use different credentials per environment
  • Document credential owners/purposes

Troubleshooting

"407 Proxy Authentication Required"

Username/Password:

  • Double-check credentials (copy-paste to avoid typos)
  • Ensure no special characters need URL encoding
  • Check if password has expired

IP Whitelist:

  • Verify your public IP: curl https://api.ipify.org
  • Check if IP changed (dynamic IPs from ISP)
  • Wait 2-3 minutes after whitelisting

API Token:

  • Check token hasn't expired
  • Verify header name matches docs (X-Proxy-Auth vs Authorization)
  • Ensure token is active in console

"Connection Refused"

  • Check proxy hostname and port
  • Verify network allows outbound connections on that port
  • Test basic connectivity: curl -v http://proxy.hbridg.com:8080

"SSL Certificate Error"

  • Use HTTPS proxy URL if available
  • Verify certificates in your client
  • Check for MITM inspection in corporate networks

Next Steps


Questions about authentication? Contact us via the console — we'll help you choose the best method for your setup.

← 返回文章列表