Missing JWT Signature Verification

Missing JWT signature verification in C#

Description

Splitting a JWT or reading it with ReadJwtToken leaves its signature unverified.

Potential impact

Using those claims for authentication or authorization can grant access as another user or with greater privileges.

Remediation

Configure JwtSecurityTokenHandler.ValidateToken or ASP.NET Core authentication middleware to verify the signature, allowed algorithm, issuer, audience and expiration.

Examples

Before

csharp
sealed class Jwt
{
    public string[] Decode(JwtValidationRequest request)
    {
        return request.Token.Split('.');
    }
}

sealed class JwtValidationRequest
{
    public string Token { get; set; } = "";
}

After

Provide the key from trusted configuration and set the issuer and audience to the actual service values. Treat validation failure as authentication failure.

csharp
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;

ClaimsPrincipal ValidateJwt(string token, SecurityKey trustedSigningKey)
{
    var validationParameters = new TokenValidationParameters
    {
        RequireSignedTokens = true,
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = trustedSigningKey,
        ValidAlgorithms = new[] { SecurityAlgorithms.RsaSha256 },
        ValidateIssuer = true,
        ValidIssuer = "https://issuer.example.com",
        ValidateAudience = true,
        ValidAudience = "api://orders",
        RequireExpirationTime = true,
        ValidateLifetime = true,
        ClockSkew = TimeSpan.FromMinutes(1)
    };

    return new JwtSecurityTokenHandler().ValidateToken(
        token, validationParameters, out _);
}

The example requires an RS256 signature and an expiration time. It allows one minute of clock skew.

References