Ключ доступа в C#
Закрытые API проверяют ключ в заголовке
"Authorization". Распространённая форма -
"Bearer", пробел и сам секрет. В
HttpClient пару имя-значение добавляют в
DefaultRequestHeaders или через
AuthenticationHeaderValue.
Учебный сервис "httpbin.org/bearer" отвечает
JSON с полем authenticated только если
заголовок передан верно. Ниже строка
"Bearer demo-token" - учебная заглушка,
не настоящий секрет; код ответа будет 200:
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using HttpClient client = new();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "demo-token");
using HttpResponseMessage response = await client.GetAsync("https://httpbin.org/bearer");
Console.WriteLine((int)response.StatusCode);
using JsonDocument doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Console.WriteLine(doc.RootElement.GetProperty("authenticated").GetBoolean());
Без заголовка тот же адрес обычно даёт отказ
401. Тело при этом не читают как успешный
ответ: смотрят StatusCode и
IsSuccessStatusCode. Каталог typicode ключ
не проверяет, поэтому отказ показывают на том же
тестовом адресе. В консоли будут код 401
и признак неуспеха:
using System.Net.Http;
using HttpClient client = new();
using HttpResponseMessage response = await client.GetAsync("https://httpbin.org/bearer");
Console.WriteLine((int)response.StatusCode);
Console.WriteLine(response.IsSuccessStatusCode);
Отправьте на "httpbin.org/bearer" запрос
с секретом "storage-key". Выведите в консоль
код ответа и поле token из JSON.