I have two applications. One is .Net 6 MVC and the other is .Net 6 web api.
When I tried to request the end point from post man I am getting headers with JWT token as expected in my api app. But If I request the same api end point from my MVC application I am getting the requested header object as null in my api app, even though If I pass the JWT token.
I also tried by creating the separate console application and checked by requesting the same api end point. but still I am getting null header value in my API side.
Below is my api code,
[Route("api/user")]
[ApiController]
public class UserController : Controller
{
private IUserRepository _userRepository = null;
public UserController(IUserRepository userRepository)
{
_userRepository = userRepository;
}
[HttpGet]
[Route("allusers")]
public List<User> GetAllUsers()
{
var headers = Request.Headers;
var userAgent = headers["User-Agent"].ToString();
var authorization = headers["Authorization"].ToString();
var test = HttpContext.Request.Headers["Authorization"];
var authHeader = Request.Headers["Authorization"].FirstOrDefault();
string userToken = authHeader?.Split(" ").Last();
var allClaims = User.Claims;
string userName = allClaims?.FirstOrDefault(x => x.Type == TokenClaims.UserName)?.Value;
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes("gdyegwuhqd9387ejnfkqk210998plnxbuqqoowsaxlKohxpqud87654hjcyg");
try
{
var validationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "GShop-WEB-API-10072023-001",
ValidAudience = "GShop-WEB-API-10072023-001",
IssuerSigningKey = new SymmetricSecurityKey(key),
// Optional: Handle clock skew for token expiration
ClockSkew = TimeSpan.Zero
};
// Validate the token and return the principal (user claims)
var principal = tokenHandler.ValidateToken(userToken, validationParameters, out SecurityToken validatedToken);
// Additional checks can be added here if needed
//return principal;
}
catch (Exception ex)
{
// Token validation failed, handle the exception
Console.WriteLine($"Token validation failed: {ex.Message}");
return null;
}
return _userRepository.GetAllUsers();
}
Below is my Program.cs file for web api app,
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
//app.UseCors("AllowSpecificOrigin");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Below is my MVC app code,
string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9zaWQiOiJjNWU5ZjU5Zi03OGRmLTQyYTYtOWQ4Ni0zODMxNmY4YTdiM2QiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6ImJoYXJhdGgiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOiJBZG1pbiIsImV4cCI6MTcyNDc0MTkxNCwiaXNzIjoiR1Nob3AtV0VCLUFQSS0xMDA3MjAyMy0wMDEiLCJhdWQiOiJHU2hvcC1XRUItQVBJLTEwMDcyMDIzLTAwMSJ9.Vi0cLnxYMXEGPinv4CyMKUVn7s12bOEMLlGaiopRq54";
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:5031/api/");
//client.DefaultRequestHeaders.Accept.Clear();
// Add necessary headers
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
// Send a GET request to the API
HttpResponseMessage apiResponse = await client.GetAsync("user/allusers");
// Ensure the request was successful
apiResponse.EnsureSuccessStatusCode();
// Read the response content as a string
string responseBody = await apiResponse.Content.ReadAsStringAsync();
// Deserialize the JSON response into a C# object
}
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);see if it helps. You can also look at your postman request and compare it with your own, something may be missing. Perhaps you also need to add CORS setting to your api.