Skip to main content

How to Validate a JWT's Issuer and Audience in .NET C# with TokenValidationParameters

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

In .NET C#, JsonWebTokenHandler.ValidateTokenAsync checks a token's issuer and audience by default. TokenValidationParameters tells it what to expect: ValidIssuer for iss and ValidAudience for aud. Leave the audience out, and every token fails with IDX10208.

Syntax​

Syntax
var parameters = new TokenValidationParameters
{
IssuerSigningKey = <key>,
ValidAlgorithms = ["<alg>"],
ValidIssuer = "<expected iss>",
ValidAudience = "<expected aud>",
};
var result = await new JsonWebTokenHandler().ValidateTokenAsync(<token>, parameters);
PartWhat it does
IssuerSigningKeyThe key that checks the signature.
ValidAlgorithmsThe signing algorithms you accept.
ValidIssuerThe iss you expect. ValidIssuers takes a list.
ValidAudienceThe aud you expect, usually your own API's name. ValidAudiences takes a list.
result.IsValidtrue when every check passed. When it's false, result.Exception says why.

Microsoft Learn describes ValidAudience as "a string that represents a valid audience that will be used to check against the token's audience. The default is null." and ValidIssuer the same way for the issuer.

The Example​

The example signs one token, issued by https://login.example.org for https://photos.example.org, and validates it four times: with the right issuer and audience, with the audience of another API, with another issuer, and with no audience at all.

Prerequisites​

  • The .NET SDK. This guide uses .NET SDK 10.0.404.

Step 1: Create the Project​

Terminal
dotnet new console -o demo
cd demo
dotnet package add Microsoft.IdentityModel.JsonWebTokens

dotnet new console makes a console app, and dotnet package add installs Microsoft.IdentityModel.JsonWebTokens, version 8.23.0 here.

Step 2: Write the Code​

Replace the contents of Program.cs:

Program.cs, which signs a token for the photos API and defines CheckAsync with ValidIssuer and ValidAudience, then checks the right pair, the videos audience, another issuer and a null audience, printing accepted or the exception message.

Program.cs
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;

// The signing key: 32 random bytes, written as base64.
// It's in the code only for this example; a real app loads it from its configuration.
var secret = Convert.FromBase64String("C4iNOOORzmu+fnrPK29yq/9n92b/zf5mOs5KvOMaY64=");
var key = new SymmetricSecurityKey(secret);
var handler = new JsonWebTokenHandler();
var token = handler.CreateToken(new SecurityTokenDescriptor
{
Issuer = "https://login.example.org",
Audience = "https://photos.example.org",
Claims = new Dictionary<string, object> { ["sub"] = "ada" },
SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256),
});

await CheckAsync("https://login.example.org", "https://photos.example.org");
await CheckAsync("https://login.example.org", "https://videos.example.org");
await CheckAsync("https://other.example.org", "https://photos.example.org");
await CheckAsync("https://login.example.org", null);

async Task CheckAsync(string issuer, string? audience)
{
var parameters = new TokenValidationParameters
{
IssuerSigningKey = key,
ValidAlgorithms = [SecurityAlgorithms.HmacSha256],
ValidIssuer = issuer,
ValidAudience = audience,
};
var result = await handler.ValidateTokenAsync(token, parameters);
if (result.IsValid)
{
Console.WriteLine($"accepted: sub {result.Claims["sub"]}");
}
else
{
Console.WriteLine($"rejected: {result.Exception.Message}");
}
}

CheckAsync is a local function at the end of Program.cs, and string? audience lets the last call pass null.

Step 3: Run It​

Terminal
dotnet run
Output
accepted: sub ada
rejected: IDX10214: Audience validation failed. See https://aka.ms/identitymodel/app-context-switches
rejected: IDX10205: Issuer validation failed. Issuer: 'https://login.example.org'. Did not match: validationParameters.ValidIssuer: 'https://other.example.org' or validationParameters.ValidIssuers: 'null' or validationParameters.ConfigurationManager.CurrentConfiguration.Issuer: 'Null'. For more details, see https://aka.ms/IdentityModel/issuer-validation.
rejected: IDX10208: Unable to validate audience. validationParameters.ValidAudience is null or whitespace and
validationParameters.ValidAudiences is null.

A zsh terminal where dotnet run prints accepted sub ada, then rejected with IDX10214 Audience validation failed, IDX10205 Issuer validation failed naming both issuers, and IDX10208 Unable to validate audience.

What Happened​

  • The right issuer and audience passed, and result.Claims held the claims.
  • The videos audience failed with IDX10214. Its message doesn't say which audiences were compared: since IdentityModel 8.8.0, it leaves out the audience data and points to a page about App Context switches, which explains the change.
  • Another issuer failed with IDX10205, and this message shows both values: the token's issuer and the expected one.
  • No audience failed with IDX10208. The audience check is on by default, and with nothing to compare against, IdentityModel rejects every token. Code whose tokens carry no aud yet has to turn the check off with ValidateAudience = false; once they do, set ValidAudience instead.

Common Mistakes​

MistakeWhat happensDo this instead
Setting ValidateAudience = false to get past IDX10208Tokens made for other APIs passSet ValidAudience to your API's name
Expecting IDX10214 to name the audiencesIt leaves them out since IdentityModel 8.8.0Decode the token and compare its aud with ValidAudience yourself
Assuming the audience comparison is as strict as the issuer oneIgnoreTrailingSlashWhenValidatingAudience is true by default, so a slash at the end of the audience doesn't countWrite audiences exactly the same everywhere anyway

Troubleshooting​

SymptomLikely causeFix
IDX10208: Unable to validate audience. validationParameters.ValidAudience is null or whitespace and validationParameters.ValidAudiences is null.No audience to compare withSet ValidAudience
IDX10214: Audience validation failed. See https://aka.ms/identitymodel/app-context-switchesThe token's aud isn't your ValidAudienceCheck which API the token was made for
IDX10205: Issuer validation failed.The token's iss isn't your ValidIssuerUse the issuer exactly as the token has it
IDX10206: Unable to validate audience. The 'audiences' parameter is empty.The token has no audHave the sign-in service set an audience

FAQ​

How do I accept tokens for several audiences?​

Set ValidAudiences to a list instead of ValidAudience. A token passes when its aud matches any of them.

Does validation fail on the first problem or report them all?​

Only the first one. A token with both the wrong issuer and the wrong audience came back with IDX10214, the audience error, because IdentityModel checks the audience before the issuer and stops at the first failure.

Conclusion​

Set ValidIssuer and ValidAudience on TokenValidationParameters. IdentityModel checks both by default and rejects tokens from other issuers or for other APIs, and the IDX code in the message says which check failed.

Additional Resources​