Improper Authentication High

Failure to verify a user's identity results in improper authentication. This can allow an attacker to acquire privileges to access sensitive data in your application.

Detector ID
csharp/improper-authentication@v1.0
Category
Common Weakness Enumeration (CWE) external icon
Tags
-

Noncompliant example

1public void ImproperAuthenticationNoncompliant(int userId)
2{
3    var mySecret = "asdv234234^&%&^%&^hjsdfb2%%%";
4    var mySecurityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(mySecret));
5    var myIssuer = "http://mysite.com";
6    var myAudience = "http://myaudience.com";
7    var tokenHandler = new JwtSecurityTokenHandler();
8    var tokenDescriptor = new SecurityTokenDescriptor
9    {
10        Subject = new ClaimsIdentity(new Claim[]
11        {
12            new Claim(ClaimTypes.NameIdentifier, userId.ToString()),
13        }),
14        Expires = DateTime.UtcNow.AddDays(7),
15        Issuer = myIssuer,
16        Audience = myAudience,
17        SigningCredentials = new SigningCredentials(mySecurityKey, SecurityAlgorithms.HmacSha256Signature)
18    };
19    // Noncompliant: `JwtSecurityTokenHandler` is not validating before using it.
20    var token = tokenHandler.CreateToken(tokenDescriptor);
21}

Compliant example

1public void ImproperAuthenticationCompliant(string token)
2{
3    var mySecret = "asdv234234^&%&^%&^hjsdfb2%%%";
4    var mySecurityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(mySecret));
5    var myIssuer = "http://mysite.com";
6    var myAudience = "http://myaudience.com";
7    var tokenHandler = new JwtSecurityTokenHandler();
8    // Compliant: `JwtSecurityTokenHandler` is validating before using it.
9    tokenHandler.ValidateToken(token, new TokenValidationParameters
10        {
11            ValidateIssuerSigningKey = true,
12            ValidateIssuer = true,
13            ValidateAudience = true,
14            ValidIssuer = myIssuer,
15            ValidAudience = myAudience,
16            IssuerSigningKey = mySecurityKey
17        }, out SecurityToken validatedToken);
18}