Skip to content

Commit

Permalink
Add SerializationBinder to restrict the object type
Browse files Browse the repository at this point in the history
  • Loading branch information
ciaozhang committed Jun 24, 2021
1 parent b263ec3 commit 1be2672
Showing 1 changed file with 31 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.IdentityModel.TestUtils;
using Xunit;
Expand Down Expand Up @@ -55,6 +56,7 @@ public void SecurityTokenInvalidIssuerExceptionSerializesValues(SecurityTokenExc

memoryStream.Seek(0, SeekOrigin.Begin);

formatter.Binder = new ExceptionSerializationBinder();
var serializedException = formatter.Deserialize(memoryStream);

theoryData.ExpectedException.ProcessNoException(context);
Expand Down Expand Up @@ -251,6 +253,35 @@ public class SecurityTokenExceptionTheoryData : TheoryDataBase

public Action<Exception> ExceptionSetter { get; set; }
}

public class ExceptionSerializationBinder : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
// One way to discover expected types is through testing deserialization
// of **valid** data and logging the types used.

//Console.WriteLine($"BindToType('{assemblyName}', '{typeName}')");

if (typeName == "Microsoft.IdentityModel.Tokens.SecurityTokenInvalidAudienceException" ||
typeName == "Microsoft.IdentityModel.Tokens.SecurityTokenInvalidIssuerException" ||
typeName == "Microsoft.IdentityModel.Tokens.SecurityTokenExpiredException" ||
typeName == "Microsoft.IdentityModel.Tokens.SecurityTokenInvalidLifetimeException" ||
typeName == "Microsoft.IdentityModel.Tokens.SecurityTokenInvalidTypeException" ||
typeName == "Microsoft.IdentityModel.Tokens.SecurityTokenNotYetValidException" ||
typeName == "Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSigningKeyException" ||
typeName == "Microsoft.IdentityModel.Tokens.SecurityTokenInvalidAlgorithmException" ||
typeName == "Microsoft.IdentityModel.Tokens.SecurityTokenUnableToValidateException" ||
typeName == "Microsoft.IdentityModel.Tokens.ValidationFailure")
{
return null;
}
else
{
throw new ArgumentException("Unexpected type: ", nameof(typeName));
}
}
}
}

#pragma warning restore CS3016 // Arrays as attribute arguments is not CLS-compliant
Expand Down

0 comments on commit 1be2672

Please sign in to comment.