Asma123
Asma123

Reputation: 11

ASP.NET Core - Token Authorization Issue between Microservices Results in 401 Unauthorized

I'm working on a microservices architecture using ASP.NET Core, with two main services: AuthService for authentication and SearchService for handling professional searches.

Users authenticate via AuthService, and I want the SearchService to retrieve user details from AuthService using a JWT token included in the Authorization header.

When I make a GET request to SearchService, it attempts to call AuthService with the token, but I keep receiving a 401 Unauthorized error from AuthService, which logs "No Authorization header found".

Here's the key part of my setup:

[Authorize]
[ApiController]
[Route("api/[controller]")]
public class ProfessionalSearchController : ControllerBase
{
    private readonly ILogger<ProfessionalSearchController> _logger;
    private readonly IHttpClientFactory _httpClientFactory;

    public ProfessionalSearchController(ILogger<ProfessionalSearchController> logger, IHttpClientFactory httpClientFactory)
    {
        _logger = logger;
        _httpClientFactory = httpClientFactory;
    }

    [HttpGet("search")]
    public async Task<IActionResult> 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<User> 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<User>();
        }

        var errorContent = await response.Content.ReadAsStringAsync();
        _logger.LogWarning($"Failed to get user by ID {userId}, StatusCode: {response.StatusCode}, Error: {errorContent}");

        return null;
    }
}

I have tried:

The logs show that AuthService isn't receiving the authorization header from SearchService, leading to the 401 Unauthorized response.

Here is the specific log:

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

Both services are running locally (AuthService on http://localhost:5203 and SearchService on http://localhost:5095).

AuthService and SearchService are configured to use JWT Bearer authentication.

Upvotes: 1

Views: 66

Answers (0)

Related Questions