0

I have a .NET Core 2 (soon to be upgraded to 3) API with JWT. This API serves several specific companies under a parent company. The parent company generates the JWT, and they set the audience specific to the requesting company (multi-company APIs are a New Thing). Therefore, my API needs to support several different audiences.

Currently, we switch dynamically based on the request URL (the company ID is in the URL). This dynamic setting happens in OnMessageReceived:

OnMessageReceived = msgRcvdContext =>
{
    companyId = GetCompanyId(msgRcvdContext.Request);
    options.TokenValidationParameters.ValidAudience = GetAudienceByCompanyId(companyId);
}

Is this changing the "global" options, rather than the options for this particular request? If this isn't the right way to serve multiple audiences, how should I do it? Should I just put all the valid audiences into a list property in TokenValidationPrameters? Or is there some other way I should do it?

Thank you.

emery.noel
  • 1,073
  • 1
  • 9
  • 24
  • This could be a job for a custom audience validator. You can set it through `TokenValidationParameters.AudienceValidator`, which has the following signature: `bool AudienceValidator(IEnumerable audiences, SecurityToken securityToken, TokenValidationParameters validationParameters)`. Seems like it supports a single token having multiple audiences, that's why the IEnumerable :) – juunas Apr 27 '20 at 13:47
  • Oh I didn't even see that. I will give it a try. Thanks! – emery.noel Apr 27 '20 at 13:54

1 Answers1

1

You can set multiple audiences via ValidAudiences property of TokenValidationParameters. See api documentation: https://learn.microsoft.com/en-us/dotnet/api/microsoft.identitymodel.tokens.tokenvalidationparameters.validaudiences?view=azure-dotnet#Microsoft_IdentityModel_Tokens_TokenValidationParameters_ValidAudiences

YankTHEcode
  • 634
  • 4
  • 8
  • @emery Did this help? – YankTHEcode May 02 '20 at 05:02
  • Hi @YankTHEcode, I was pulled off the project before I had a chance to implement it, and had since forgotten about this question. Just today, someone is experiencing issues that sound like what I was worried about, so they are doing investigation. If this is the answer I will mark it so, I expect to know soon-ish, like 1-2 weeks. Thanks for the info! – emery.noel Jan 21 '21 at 14:00