Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I send additional authorization id?

I've got a case where in every request that goes to api there's property like

public Guid CompanyId {get; set;}

It is then checked with UserId from JWT token to check if user has access to that particular company.

I don't want that property to be in every call to the api. Is there a better way to approach that, like creating custom claim in JWT token?

It gets a bit more complicated cause users can have access to more that one company, so if I were to go with the custom claim, is there any way to refresh the token and change claim value in it?

like image 427
Kacper Gwiazdowski Avatar asked Mar 28 '26 19:03

Kacper Gwiazdowski


1 Answers

You can have a similar function to issue Tokens for your users and pass in current session company Id and add it to them claims

public string IssueToken(Guid userId, Guid companyId)
{
  
  SigningCredentials siginingCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SuperSecretKey")), SecurityAlgorithms.HmacSha256Signature);

  JwtSecurityToken token = new JwtSecurityToken(
    issuer: "Issuer",
    audience: "Audience",
    expires: DateTime.UtcNow.AddMinutes(5),
    signingCredentials: siginingCredentials,
    claims: new List<Claim>
            {

                new Claim("companyId",companyId.ToString()),
                new Claim(JwtRegisteredClaimNames.Sub,userId.ToString())
            }
   );

   return new JwtSecurityTokenHandler().WriteToken(token);
}

and then later on you can access them by using HttpContextAccessor

Guid? UserId = Guid.Parse(_httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier));
Guid? CompanyId = Guid.Parse(_httpContextAccessor.HttpContext.User.FindFirstValue("companyId"));
like image 177
Ashkan Afsharpour Avatar answered Mar 31 '26 06:03

Ashkan Afsharpour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!