Когда я делаю запрос GET к SearchService, он пытается вызвать AuthService с помощью токена, но я Продолжайте получать ошибку 401 Unauthorized от AuthService, которая регистрирует отсутствие заголовка авторизации. Вот ключевая часть моей настройки:
Код: Выделить всё
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class ProfessionalSearchController : ControllerBase
{
private readonly ILogger
_logger;
private readonly IHttpClientFactory _httpClientFactory;
public ProfessionalSearchController(ILogger logger, IHttpClientFactory httpClientFactory)
{
_logger = logger;
_httpClientFactory = httpClientFactory;
}
[HttpGet("search")]
public async Task SearchProfessionals([FromQuery] string specialisation)
{
var userId = User.FindFirst("uid")?.Value;
if (userId == null)
{
_logger.LogWarning("User ID not found in token");
return Unauthorized();
}
var patient = await GetUserById(userId);
if (patient == null)
{
_logger.LogWarning("Patient not found");
return NotFound("Patient not found.");
}
// Rest of the code...
}
private async Task GetUserById(string userId)
{
var token = Request.Headers["Authorization"].ToString();
if (string.IsNullOrEmpty(token))
{
_logger.LogWarning("No token provided.");
return null;
}
var client = _httpClientFactory.CreateClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", ""));
var response = await client.GetAsync($"http://localhost:5203/api/User/{userId}");
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadFromJsonAsync();
}
var errorContent = await response.Content.ReadAsStringAsync();
_logger.LogWarning($"Failed to get user by ID {userId}, StatusCode: {response.StatusCode}, Error: {errorContent}");
return null;
}
Я пробовал: проверил, что токен содержит необходимые утверждения, включая роли.
Подтвердил, что заголовок авторизации в запрос SearchService к AuthService установлен как Bearer {token}.
Убедились, что обе службы используют одинаковые параметры проверки токена (эмитент, аудитория и ключ подписи).
Протестировали конечную точку в Postman, напрямую вызвав AuthService, что отлично работает с тем же токеном.
Журналы показывают, что AuthService не получает заголовок авторизации от SearchService, что приводит к ответу 401 Unauthorized. Вот конкретный журнал:
Код: Выделить всё
System.Net.Http.HttpClient.Default.LogicalHandler: Information:
Start processing HTTP request GET
http://localhost:5203/api/User/b4e60ba8-79fa-4c33-a862-
f60d06213d6b
System.Net.Http.HttpClient.Default.ClientHandler: Information:
Sending HTTP request GET http://localhost:5203/api/User/b4e60ba8-
79fa-4c33-a862-f60d06213d6b
BackendDocVillage.Startup: Information: Request Method: GET, Path:
/api/User/b4e60ba8-79fa-4c33-a862-f60d06213d6b
BackendDocVillage.Startup: Information: Received Token: Bearer
eyJhbGci..
BackendDocVillage.Startup: Information: Request Method: GET, Path:
/api/User/b4e60ba8-79fa-4c33-a862-f60d06213d6b
BackendDocVillage.Startup: Information: No Authorization header
found.
System.Net.Http.HttpClient.Default.ClientHandler: Information:
Received HTTP response headers after 38.9651ms - 401
System.Net.Http.HttpClient.Default.LogicalHandler: Information:
End processing HTTP request after 52.6424ms - 401
SearchService.Controllers.ProfessionalSearchController: Warning:
Failed to get user by ID b4e60ba8-79fa-4c33-a862-f60d06213d6b,
StatusCode: Unauthorized, Error:
SearchService.Controllers.ProfessionalSearchController: Warning:
Patient not found
Обе службы работают локально (AuthService на http://localhost:5203 и SearchService на http://localhost:5095).
AuthService и SearchService настроены на использование аутентификации носителя JWT.
Подробнее здесь: https://stackoverflow.com/questions/791 ... -in-401-un