You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用C# HttpClient实现Bearer Token与Basic Auth双重认证

How to Implement Dual Authentication (Basic + Bearer Token) with HttpClient

Got it, let's walk through exactly how to handle this dual authentication flow with HttpClient. Since your server now requires both Basic authentication (for server-level validation) and your existing Bearer Token (for API-level authorization), here's how to implement this smoothly, depending on your server's specific behavior:

Scenario 1: Every Request Needs Both Basic and Bearer Auth

If your server checks for both Basic credentials and Bearer Token on every API call (e.g., a reverse proxy handles Basic auth before passing the request to your API which uses Bearer Tokens), you'll need to include both authentication headers in each request.

Here's a complete C# example:

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

class DualAuthExample
{
    static async Task Main(string[] args)
    {
        // 1. Configure Basic Auth credentials
        string basicUsername = "your-basic-username";
        string basicPassword = "your-basic-password";
        var basicAuthBytes = Encoding.ASCII.GetBytes($"{basicUsername}:{basicPassword}");
        string basicAuthBase64 = Convert.ToBase64String(basicAuthBytes);

        // 2. Initialize HttpClient (reuse this instance for all requests!)
        using var httpClient = new HttpClient();

        // 3. Prepare the API request with both auth headers
        string apiEndpoint = "https://your-api-server.com/protected-endpoint";
        string bearerToken = "your-valid-bearer-token";

        var request = new HttpRequestMessage(HttpMethod.Get, apiEndpoint);
        
        // Add both Authorization headers (some servers allow multiple; adjust if needed)
        request.Headers.Add("Authorization", $"Basic {basicAuthBase64}");
        request.Headers.Add("Authorization", $"Bearer {bearerToken}");

        // Send the request and handle the response
        var response = await httpClient.SendAsync(request);
        response.EnsureSuccessStatusCode(); // Throws if status code is 4xx/5xx

        var responseContent = await response.Content.ReadAsStringAsync();
        Console.WriteLine("API Response: " + responseContent);
    }
}

Key Notes:

  • Reuse HttpClient: Never create a new HttpClient for every request—this causes socket exhaustion issues. Reuse a single instance for your app's lifecycle.
  • Multiple Authorization Headers: Not all servers support multiple Authorization headers. If yours rejects this, check if it expects a custom header for one of the auth types (e.g., X-Basic-Auth instead of the standard Authorization for Basic credentials).

Scenario 2: Basic Auth to Get a Session, Then Bearer Token for API Calls

If your server requires you to first authenticate with Basic credentials to establish a session (e.g., set a session cookie), then use your Bearer Token for subsequent API requests, follow this flow:

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

class SessionBasedAuthExample
{
    static async Task Main(string[] args)
    {
        string basicUsername = "your-basic-username";
        string basicPassword = "your-basic-password";
        string bearerToken = "your-valid-bearer-token";
        string authEndpoint = "https://your-api-server.com/auth"; // Endpoint to establish session
        string apiEndpoint = "https://your-api-server.com/protected-endpoint";

        // Use HttpClientHandler to automatically persist cookies
        var handler = new HttpClientHandler();
        using var httpClient = new HttpClient(handler);

        // Step 1: Send Basic Auth request to get session cookie
        var basicAuthBytes = Encoding.ASCII.GetBytes($"{basicUsername}:{basicPassword}");
        string basicAuthBase64 = Convert.ToBase64String(basicAuthBytes);

        var authRequest = new HttpRequestMessage(HttpMethod.Post, authEndpoint);
        authRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", basicAuthBase64);
        
        var authResponse = await httpClient.SendAsync(authRequest);
        authResponse.EnsureSuccessStatusCode();

        // Step 2: Send API request with Bearer Token (cookie is automatically included)
        var apiRequest = new HttpRequestMessage(HttpMethod.Get, apiEndpoint);
        apiRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
        
        var apiResponse = await httpClient.SendAsync(apiRequest);
        apiResponse.EnsureSuccessStatusCode();

        var responseContent = await apiResponse.Content.ReadAsStringAsync();
        Console.WriteLine("API Response: " + responseContent);
    }
}

Key Notes:

  • Cookie Persistence: The HttpClientHandler automatically stores cookies from the auth response, so subsequent requests to the same domain will include them automatically.
  • Session Expiry: Make sure to handle session expiry (e.g., re-authenticate with Basic credentials if you get a 401 Unauthorized response after the session expires).

内容的提问来源于stack exchange,提问作者Erik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:10:44