How to get other API Request url in my Api and set in Audience ?

om_mkwn 0 Reputation points
2025-02-25T09:53:18.8133333+00:00

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 ?

Community Center Not monitored
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Pradeep M 9,765 Reputation points Microsoft External Staff Volunteer Moderator
    2025-02-25T11:03:11.9033333+00:00

    Hi om_mkwn,

    Thank you for reaching out to Microsoft Q & A forum. 

    Set the Audience in IoApi's GenerateToken method to include MainApi's URL, ensuring MainApi can validate and use the token correctly. 

    Modify GenerateToken in IoApi: 

    new Claim(JwtRegisteredClaimNames.Aud, "http://localhost:5000") // MainApi URL
    
    
    

    Or allow multiple audiences: 

    new Claim("aud", "http://localhost:5000,http://localhost:5173")
    
    

    Configure IoApi to Accept MainApi 

    In appsettings.json: 

    "ValidAudiences": ["http://localhost:5000", "http://localhost:5173"]
    
    

    In Program.cs: 

    options.Audience = "http://localhost:5000";
    
    

    This ensures MainApi can call IoApi with a valid token.

    Please feel free to contact us if you have any additional questions.     

    If you have found the answer provided to be helpful, please click on the "Accept answer/Upvote" button so that it is useful for other members in the Microsoft Q&A community.  

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.