So i have two apis MainApi and IoApi.
So i try to set JWT token vise authentication, when i try to get data from IoApi so first of all get Token and than get authorize data.
but in my case i set the Audience and i try to get data from another Api so there are also get the authorize data.
so i try to set the MainApi url set in my IoApi Audience but there are not get MainApi url on it...
so this is my Api code :
MainApi :
[HttpGet]
[Route("GetInputByID1")]
public async Task<IActionResult> GetInputByID1()
{
try
{
var tokenResponse = await client.GetAsync("http://localhost:5173/api/Auth/GenerateToken");
if (!tokenResponse.IsSuccessStatusCode)
{
return StatusCode((int)tokenResponse.StatusCode, "Failed to get JWT token from DBAPI.");
}
var tokenResult = await tokenResponse.Content.ReadAsStringAsync();
var tokenObj = JsonConvert.DeserializeObject<dynamic>(tokenResult);
string jwtToken = tokenObj?.token;
return Ok(jwtToken);
}
catch (Exception ex)
{
_logger.LogError($"Error: {ex.Message}");
return StatusCode(500, $"An error occurred: {ex.Message}");
}
}
IoApi :
[HttpGet("GenerateToken")]
public IActionResult GenerateToken()
{
var request = HttpContext.Request;
string callerUrl =$"{ request.Scheme }://{ request.Host }{ request.Path }{ request.QueryString }";
_logger.LogInformation($"base ....... {callerUrl}");
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("sJw1Pq5/D2S98XTX7h0IrsnZ5/Eih8XocFq58a0vIVY="));
var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Iss, "http://localhost:5173"),
new Claim(JwtRegisteredClaimNames.Aud, callerUrl)
};
var tokenOptions = new JwtSecurityToken(
issuer: "http://localhost:5173",
audience: callerUrl,
claims: claims,
expires: DateTime.UtcNow.AddMinutes(30),
signingCredentials: signinCredentials
);
var tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOptions);
return Ok(new { Token = tokenString });
}
[Authorize]
[HttpGet]
public IActionResult GetData()
{
return Ok(new { message = "Protected data retrieved successfully!" });
}
so when i call my MainApi to IoApi
there are not set the MainApi url in my IoApi
so how to do MainApi request url set in my Audience ?