I am having two applications. One is .Net 6 MVC and another one is .Net 6 Web api.
I am generating the JWT token in my web api application. When I try to access one Authorize end point by passing the JWT token in postman I am getting 200 OK response, but when I try to access the same Authorize end point by passing the same JWT token from my MVC application, then I am getting 401 unauthorized response.
This is the problem which I am facing. Some one help me to resolve this issue.
Below is the MVC code which I am trying to access the end point.
public async Task<List<T>> GetApiList<T>(string serviceUrl, string userToken = null, bool isAuth = true) where T : new()
{
List<T> response = new List<T>();
try
{
using (HttpClient client = new HttpClient())
{
// Add necessary headers
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
// Send a GET request to the API
HttpResponseMessage apiResponse = await client.GetAsync("http://localhost:5031/api/" + "gallery/authtestapi");
// 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
response = JsonConvert.DeserializeObject<List<T>>(responseBody);
return response;
}
}
catch (HttpRequestException httpEx)
{
// Log the HTTP request exception (e.g., 401 Unauthorized)
Console.WriteLine($"HTTP Request Exception: {httpEx.Message}");
return response;
}
catch (Exception ex)
{
return response;
}
}
Below is the code which I am trying to access in web api.
[HttpGet]
[Route("authtestapi")]
[Authorize]
public string AuthTestApi()
{
return "Response from authorize api";
}
Below is the api code to generate the JWT token.
//generating jwt token
var claims = new[]
{
new Claim(ClaimTypes.Sid,user.Id),
new Claim(ClaimTypes.NameIdentifier,user.UserName),
new Claim(ClaimTypes.Role,userRoles[0])
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("gdyegwuhqd9387ejnfkqk210998plnxbuqqoowsaxlKohxpqud87654hjcyg"));
var token = new JwtSecurityToken(
issuer: "GShop-WEB-API-10072023-001",
audience: "GShop-WEB-API-10072023-001",
claims: claims,
expires: DateTime.Now.AddDays(30),
signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
);
string tokenAsString = new JwtSecurityTokenHandler().WriteToken(token);
Below is the Program.cs configuration code in api code.
//add jwt authentication
builder.Services.AddAuthentication(auth =>
{
auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
auth.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidIssuer = "GShop-WEB-API-10072023-001",
ValidAudience = "GShop-WEB-API-10072023-001",
RequireExpirationTime = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("gdyegwuhqd9387ejnfkqk210998plnxbuqqoowsaxlKohxpqud87654hjcyg")),
ValidateIssuerSigningKey = true,
};
});
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.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();