Broken JSON Web Token in .NET
Prevention
ASP.NET Core natively provides JWT authentication through the middleware Microsoft.AspNetCore.Authentication.JwtBearer package.
The JWT bearer authentication can be enabled in the app’s Startup.Configure
method by using the UseJwtBearerAuthentication
extension method, or by setting the scheme to JwtBearerDefaults.AuthenticationScheme
using services.AddAuthentication()
.
The authentication options TokenValidationParameters
describe how JWT tokens will be validated. The class supports a large number of parameters, some of them are illustrated in the code snippet below:
var tokenValidationParameters = new TokenValidationParameters
{
RequireSignedTokens = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = true,
ValidateLifetime = true,
ValidateAudience = true
};
-
RequireSignedTokens
indicates whether a SecurityToken can be considered valid if not signed. Set totrue
to enable basic validation for JWT tokens. -
IssuerSigningKey
is the key used for validating incoming JWT tokens. By specifying a key here, the token can be validated without assistance from the issuing server. -
ValidateIssuer
enforces issuer validation. -
ValidateLifetime
enforces lifetime validation. -
ValidateAudience
enforces audience validation.
It’s vital that if a symmetric key is used as IssuerSigningKey
, it must be a strong secret with sufficient entropy to avoid being compromised by attackers forging valid tokens.
References
Auth0 - Critical vulnerabilities in JSON Web Token libraries Auth0 - JWT Debugger MSDN - JWT Validation and Authorization in ASP.NET Core