Skip to content

Commit

Permalink
Set TokenValidationResult.IsValid to false if Exception is thrown.
Browse files Browse the repository at this point in the history
If TokenValidationResult.Exception is non null, IsValid should be false.
Add some comments to GetSetContext
  • Loading branch information
brentschmaltz committed Jun 26, 2020
1 parent 3744a01 commit aab47fa
Show file tree
Hide file tree
Showing 7 changed files with 116 additions and 9 deletions.
11 changes: 6 additions & 5 deletions src/Microsoft.IdentityModel.JsonWebTokens/JsonWebTokenHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1049,17 +1049,17 @@ public virtual SecurityToken ReadToken(string token)
public virtual TokenValidationResult ValidateToken(string token, TokenValidationParameters validationParameters)
{
if (string.IsNullOrEmpty(token))
return new TokenValidationResult { Exception = LogHelper.LogArgumentNullException(nameof(token)) };
return new TokenValidationResult { Exception = LogHelper.LogArgumentNullException(nameof(token)), IsValid = false };

if (validationParameters == null)
return new TokenValidationResult { Exception = LogHelper.LogArgumentNullException(nameof(validationParameters)) };
return new TokenValidationResult { Exception = LogHelper.LogArgumentNullException(nameof(validationParameters)), IsValid = false };

if (token.Length > MaximumTokenSizeInBytes)
return new TokenValidationResult { Exception = LogHelper.LogExceptionMessage(new ArgumentException(LogHelper.FormatInvariant(TokenLogMessages.IDX10209, token.Length, MaximumTokenSizeInBytes))) };
return new TokenValidationResult { Exception = LogHelper.LogExceptionMessage(new ArgumentException(LogHelper.FormatInvariant(TokenLogMessages.IDX10209, token.Length, MaximumTokenSizeInBytes))), IsValid = false };

var tokenParts = token.Split(new char[] { '.' }, JwtConstants.MaxJwtSegmentCount + 1);
if (tokenParts.Length != JwtConstants.JwsSegmentCount && tokenParts.Length != JwtConstants.JweSegmentCount)
return new TokenValidationResult { Exception = LogHelper.LogExceptionMessage(new ArgumentException(LogHelper.FormatInvariant(LogMessages.IDX14111, token))) };
return new TokenValidationResult { Exception = LogHelper.LogExceptionMessage(new ArgumentException(LogHelper.FormatInvariant(LogMessages.IDX14111, token))), IsValid = false };

try
{
Expand Down Expand Up @@ -1088,7 +1088,8 @@ public virtual TokenValidationResult ValidateToken(string token, TokenValidation
{
return new TokenValidationResult
{
Exception = ex
Exception = ex,
IsValid = false
};
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1844,7 +1844,12 @@ public void ValidateJWS(JwtTheoryData theoryData)
var handler = new JsonWebTokenHandler();
var validationResult = handler.ValidateToken(theoryData.Token, theoryData.ValidationParameters);
if (validationResult.Exception != null)
{
if (validationResult.IsValid)
context.AddDiff("validationResult.IsValid, validationResult.Exception != null");

throw validationResult.Exception;
}

theoryData.ExpectedException.ProcessNoException(context);
}
Expand Down Expand Up @@ -2356,7 +2361,12 @@ public void JWEDecompressionTest(JWEDecompressionTheoryData theoryData)
var validationResult = handler.ValidateToken(theoryData.JWECompressionString, theoryData.ValidationParameters);
var validatedToken = validationResult.SecurityToken as JsonWebToken;
if (validationResult.Exception != null)
{
if (validationResult.IsValid)
context.AddDiff("validationResult.IsValid, validationResult.Exception != null");

throw validationResult.Exception;
}

if (validationResult.IsValid)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1390,7 +1390,12 @@ public async Task ValidateSignedHttpRequest(ValidateSignedHttpRequestTheoryData
var result = await handler.ValidateSignedHttpRequestAsync(signedHttpRequestValidationContext, CancellationToken.None).ConfigureAwait(false);

if (result.Exception != null)
{
if (result.IsValid)
context.AddDiff("result.IsValid, result.Exception != null");

throw result.Exception;
}

theoryData.ExpectedException.ProcessNoException(context);
}
Expand Down
14 changes: 11 additions & 3 deletions test/Microsoft.IdentityModel.TestUtils/TestUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,22 @@ namespace Microsoft.IdentityModel.TestUtils
{
public class GetSetContext
{
private List<string> _errors = new List<string>();

private List<KeyValuePair<string, List<object>>> _propertyNamesAndSetGetValues;

public List<string> Errors { get { return _errors; } }
/// <summary>
/// Any errors will be put here.
/// </summary>
public List<string> Errors { get; } = new List<string>();

/// <summary>
/// The 'TKey' in <see cref="KeyValuePair{TKey, TValue}"/> is the name of the Method to call.
/// The first 'TValue' is the default value, the others will be used to perform a 'set / get' and then check values are equal. This catches the error where an assignment is made to the wrong private variable.
/// </summary>
public List<KeyValuePair<string, List<object>>> PropertyNamesAndSetGetValue { get { return _propertyNamesAndSetGetValues; } set { _propertyNamesAndSetGetValues = value; } }

/// <summary>
/// This is an instance of the object that is to be tested.
/// </summary>
public object Object { get; set; }
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ void action()
var jwt = theoryData.JwtSecurityTokenHandler.CreateEncodedJwt(theoryData.TokenDescriptor);
var claimsPrincipal = theoryData.JwtSecurityTokenHandler.ValidateToken(theoryData.Jwt, theoryData.ValidationParameters, out SecurityToken _);
var tokenValidationResult = theoryData.JsonWebTokenHandler.ValidateToken(theoryData.Jwt, theoryData.ValidationParameters);

if (tokenValidationResult.Exception != null && tokenValidationResult.IsValid)
context.Diffs.Add("tokenValidationResult.IsValid, tokenValidationResult.Exception != null");

if (!tokenValidationResult.IsValid)
{
numberOfErrors++;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
//------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Security.Claims;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.TestUtils;
using Xunit;

namespace Microsoft.IdentityModel.Tokens.Tests
{
public class TokenValidationResultTests
{
[Fact]
public void GetSets()
{
TestUtilities.WriteHeader("TokenValidationResultTests.GetSets()");

TokenValidationResult tokenValidationResult = new TokenValidationResult();
Type type = typeof(TokenValidationResult);
PropertyInfo[] properties = type.GetProperties();
if (properties.Length != 7)
Assert.True(false, "Number of public fields has changed from 7 to: " + properties.Length + ", adjust tests");

GetSetContext context =
new GetSetContext
{
PropertyNamesAndSetGetValue = new List<KeyValuePair<string, List<object>>>
{
new KeyValuePair<string, List<object>>("ClaimsIdentity", new List<object>{(ClaimsIdentity)null, new ClaimsIdentity(), new ClaimsIdentity()}),
new KeyValuePair<string, List<object>>("Exception", new List<object>{(Exception)null, new Exception(), new Exception()}),
new KeyValuePair<string, List<object>>("Issuer", new List<object>{(string)null, "issuer", "issuer2"}),
new KeyValuePair<string, List<object>>("IsValid", new List<object>{false, false, true}),
new KeyValuePair<string, List<object>>("SecurityToken", new List<object>{(SecurityToken)null, new JsonWebToken(Default.Jwt(Default.SecurityTokenDescriptor())), new JsonWebToken(Default.Jwt(Default.SecurityTokenDescriptor()))}),
new KeyValuePair<string, List<object>>("TokenContext", new List<object>{(CallContext)null, new CallContext(), new CallContext()}),
new KeyValuePair<string, List<object>>("TokenType", new List<object>{(string)null, "JWTToken", "JwtToken2"}),
},
Object = tokenValidationResult,
};

TestUtilities.GetSet(context);

TestUtilities.AssertFailIfErrors("TokenValidationResultTests.GetSets", context.Errors);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,17 @@ public void CreateJWEUsingSecurityTokenDescriptor(CreateTokenTheoryData theoryDa
var claimsPrincipal = theoryData.JwtSecurityTokenHandler.ValidateToken(tokenFromTokenDescriptor, theoryData.ValidationParameters, out SecurityToken validatedTokenFromJwtHandler);
var validationResult = theoryData.JsonWebTokenHandler.ValidateToken(jweFromJsonHandler, theoryData.ValidationParameters);

if (validationResult.Exception != null && validationResult.IsValid)
context.Diffs.Add("validationResult.IsValid, validationResult.Exception != null");

IdentityComparer.AreEqual(validationResult.IsValid, theoryData.IsValid, context);
var validatedTokenFromJsonHandler = validationResult.SecurityToken;
var validationResult2 = theoryData.JsonWebTokenHandler.ValidateToken(tokenFromTokenDescriptor, theoryData.ValidationParameters);
IdentityComparer.AreEqual(validationResult.IsValid, theoryData.IsValid, context);

if (validationResult2.Exception != null && validationResult2.IsValid)
context.Diffs.Add("validationResult2.IsValid, validationResult2.Exception != null");

IdentityComparer.AreEqual(validationResult2.IsValid, theoryData.IsValid, context);
IdentityComparer.AreEqual(claimsPrincipal.Identity, validationResult.ClaimsIdentity, context);
IdentityComparer.AreEqual((validatedTokenFromJwtHandler as JwtSecurityToken).Claims, (validatedTokenFromJsonHandler as JsonWebToken).Claims, context);

Expand Down

0 comments on commit aab47fa

Please sign in to comment.