-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathJavaScriptTypeResolver.xml
More file actions
366 lines (323 loc) · 17.4 KB
/
JavaScriptTypeResolver.xml
File metadata and controls
366 lines (323 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
<Type Name="JavaScriptTypeResolver" FullName="System.Web.Script.Serialization.JavaScriptTypeResolver">
<TypeSignature Language="C#" Value="public abstract class JavaScriptTypeResolver" />
<TypeSignature Language="ILAsm" Value=".class public auto ansi abstract beforefieldinit JavaScriptTypeResolver extends System.Object" />
<TypeSignature Language="DocId" Value="T:System.Web.Script.Serialization.JavaScriptTypeResolver" />
<TypeSignature Language="VB.NET" Value="Public MustInherit Class JavaScriptTypeResolver" />
<TypeSignature Language="F#" Value="type JavaScriptTypeResolver = class" />
<TypeSignature Language="C++ CLI" Value="public ref class JavaScriptTypeResolver abstract" />
<AssemblyInfo>
<AssemblyName>System.Web.Extensions</AssemblyName>
<AssemblyVersion>3.5.0.0</AssemblyVersion>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
</AssemblyInfo>
<Base>
<BaseTypeName>System.Object</BaseTypeName>
</Base>
<Interfaces />
<Docs>
<summary>Provides the abstract base class for implementing a custom type resolver.</summary>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
The <xref:System.Web.Script.Serialization.JavaScriptTypeResolver> class provides the services for:
- Converting managed type information to a string value through the <xref:System.Web.Script.Serialization.JavaScriptTypeResolver.ResolveTypeId%2A> method.
- Resolving a string value back to the appropriate managed type through the <xref:System.Web.Script.Serialization.JavaScriptTypeResolver.ResolveType%2A> method.
When the <xref:System.Web.Script.Serialization.JavaScriptSerializer> object serializes custom types, it can optionally include in the serialized JavaScript Object Notation (JSON) string a value that contains type information. During deserialization, <xref:System.Web.Script.Serialization.JavaScriptSerializer> can then reference this string value to determine the appropriate managed type to which the JSON string will be converted.
If you provide a type resolver to the <xref:System.Web.Script.Serialization.JavaScriptSerializer> instance, the serializer will use the <xref:System.Web.Script.Serialization.JavaScriptTypeResolver.ResolveTypeId%2A> and <xref:System.Web.Script.Serialization.JavaScriptTypeResolver.ResolveType%2A> methods to map between the managed type and the string value during the serialization and deserialization process, respectively.
The <xref:System.Web.Script.Serialization.JavaScriptTypeResolver> class is the base class for the <xref:System.Web.Script.Serialization.SimpleTypeResolver> class, which provides an implementation of a type resolver that uses the managed type assembly-qualified name.
> [!NOTE]
> When using a `JavaScriptTypeResolver`, the resulting JSON payload contains a special `__type` property. This property includes the full type name, including namespace, of the target type. Before using a custom resolver, verify that the full name of the target type does not contain sensitive or privileged information.
## Examples
The following example shows how to create a custom `JavaScriptTypeResolver` and how to use it to serialize or deserialize an object.
```csharp
using System;
using System.Linq;
using System.Web.Script.Serialization;
namespace SampleApp
{
class Program
{
static void Main(string[] args)
{
// The object array to serialize.
Person[] people = new Person[]
{
new Person()
{
Name = "Kristen Solstad",
Age = 15,
HomeAddress = new Address()
{
Street1 = "123 Palm Ave",
City = "Some City",
StateOrProvince = "ST",
Country = "United States",
PostalCode = "00000"
}
},
new Adult()
{
Name = "Alex Johnson",
Age = 39,
Occupation = "Mechanic",
HomeAddress = new Address()
{
Street1 = "445 Lorry Way",
Street2 = "Unit 3A",
City = "Some City",
Country = "United Kingdom",
PostalCode = "AA0 A00"
}
}
};
// Serialize the object array, then write it to the console.
string serializedData = SerializePeopleArray(people);
Console.WriteLine("Serialized:");
Console.WriteLine(serializedData);
Console.WriteLine();
// Now deserialize the object array.
Person[] deserializedArray = DeserializePeopleArray(serializedData);
Console.WriteLine("Deserialized " + deserializedArray.Length + " people.");
foreach (Person person in deserializedArray)
{
Console.WriteLine(person.Name + " (Age " + person.Age + ") [" + person.GetType() + "]");
}
}
static string SerializePeopleArray(Person[] people)
{
// The custom type resolver to use.
// Note: Except for primitives like int and string, *every* type that
// we might see in the object graph must be listed here.
CustomTypeResolver resolver = new CustomTypeResolver(
typeof(Person),
typeof(Adult),
typeof(Address));
// Instantiate the serializer.
JavaScriptSerializer serializer = new JavaScriptSerializer(resolver);
// Serialize the object array, then return it.
string serialized = serializer.Serialize(people);
return serialized;
}
static Person[] DeserializePeopleArray(string serializedData)
{
// The custom type resolver to use.
// Note: This is the same list that was provided to the Serialize routine.
CustomTypeResolver resolver = new CustomTypeResolver(
typeof(Person),
typeof(Adult),
typeof(Address));
// Instantiate the serializer.
JavaScriptSerializer serializer = new JavaScriptSerializer(resolver);
// Deserialize the object array, then return it.
Person[] deserialized = serializer.Deserialize<Person[]>(serializedData);
return deserialized;
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Address HomeAddress { get; set; }
}
public class Adult : Person
{
public string Occupation { get; set; }
}
public class Address
{
public string Street1 { get; set; }
public string Street2 { get; set; }
public string City { get; set; }
public string StateOrProvince { get; set; }
public string Country { get; set; }
public string PostalCode { get; set; }
}
// A custom JavaScriptTypeResolver that restricts the payload
// to a set of known good types.
class CustomTypeResolver : JavaScriptTypeResolver
{
private readonly Type[] _allowedTypes;
public CustomTypeResolver(params Type[] allowedTypes)
{
if (allowedTypes == null)
{
throw new ArgumentNullException("allowedTypes");
}
// Make a copy of the array the caller gave us.
_allowedTypes = (Type[])allowedTypes.Clone();
}
public override Type ResolveType(string id)
{
// Iterate over all of the allowed types, looking for a match
// for the 'id' parameter. Calling Type.GetType(id) is dangerous,
// so we instead perform a match on the Type.FullName property.
foreach (Type allowedType in _allowedTypes)
{
if (allowedType.FullName == id)
{
return allowedType;
}
}
// The caller provided a type we don't recognize. This could be
// dangerous, so we'll fail the operation immediately.
throw new ArgumentException("Unknown type: " + id, "id");
}
public override string ResolveTypeId(Type type)
{
// Before we serialize data, quickly double-check to make
// sure we're allowed to deserialize the data. Otherwise it's
// no good serializing something if we can't deserialize it.
if (_allowedTypes.Contains(type))
{
return type.FullName;
}
throw new InvalidOperationException("Cannot serialize an object of type " + type + ". Did you forget to add it to the allow list?");
}
}
}
```
The preceding app outputs the following to the console, formatted for readability.
```txt
Serialized:
[
{
"__type": "SampleApp.Person",
"Name": "Kristen Solstad",
"Age": 15,
"HomeAddress": {
"__type": "SampleApp.Address",
"Street1": "123 Palm Ave",
"Street2": null,
"City": "Some City",
"StateOrProvince": "ST",
"Country": "United States",
"PostalCode": "00000"
}
},
{
"__type": "SampleApp.Adult",
"Occupation": "Mechanic",
"Name": "Alex Johnson",
"Age": 39,
"HomeAddress": {
"__type": "SampleApp.Address",
"Street1": "445 Lorry Way",
"Street2": "Unit 3A",
"City": "Some City",
"StateOrProvince": null,
"Country": "United Kingdom",
"PostalCode": "AA0 A00"
}
}
]
Deserialized 2 people.
Kristen Solstad (Age 15) [SampleApp.Person]
Alex Johnson (Age 39) [SampleApp.Adult]
```
In the preceding sample, the `Adult` type subclasses the `Person` type. A custom `JavaScriptTypeResolver` is used to include the type information as part of the generated JSON payload. This allows limited polymorphism when deserializing the JSON payload back into a .NET object graph. The payload can control whether to return a base `Person` instance or a derived `Adult` instance back to the caller.
This sample is safe because it uses an `allow-list` mechanism to control deserialization. The code:
* Initializes the `CustomTypeResolver` with an explicit list of allowed types.
* Restricts the deserialization process to only approved list of types. The restriction prevents [deserialization attacks](https://owasp.org/www-community/vulnerabilities/Deserialization_of_untrusted_data), where the remote client specifies a malicious `__type` in the JSON payload and tricks the server into deserializing a dangerous type.
Even though the app only expects `Person` and `Adult` instances to be deserialized as part of the top-level array, it's still necessary to add `Address` to the allow-list because:
* Serializing a `Person` or `Adult` also serializes an `Address` as part of the object graph.
* All types that might be present in the object graph need to be accounted for in the allow list. Primitives like `int` and `string` do not need to be specified.
> [!WARNING]
> Do not call `Type.GetType(id)` within the `ResolveType` method. This could introduce a security vunerability into the app. Instead, iterate through the list of allowed types and compare their `Type.FullName` property against the incoming `id`, as shown in the preceding sample.
]]></format>
</remarks>
<block subset="none" type="overrides">
<para>When you implement a type resolver, the string that is returned by the <see cref="M:System.Web.Script.Serialization.JavaScriptTypeResolver.ResolveTypeId(System.Type)" /> method must map back to the same managed type when the string value is passed to the <see cref="M:System.Web.Script.Serialization.JavaScriptTypeResolver.ResolveType(System.String)" /> method.</para>
</block>
</Docs>
<Members>
<Member MemberName=".ctor">
<MemberSignature Language="C#" Value="protected JavaScriptTypeResolver ();" />
<MemberSignature Language="ILAsm" Value=".method familyhidebysig specialname rtspecialname instance void .ctor() cil managed" />
<MemberSignature Language="DocId" Value="M:System.Web.Script.Serialization.JavaScriptTypeResolver.#ctor" />
<MemberSignature Language="VB.NET" Value="Protected Sub New ()" />
<MemberSignature Language="C++ CLI" Value="protected:
 JavaScriptTypeResolver();" />
<MemberType>Constructor</MemberType>
<AssemblyInfo>
<AssemblyName>System.Web.Extensions</AssemblyName>
<AssemblyVersion>3.5.0.0</AssemblyVersion>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
</AssemblyInfo>
<Attributes>
<Attribute FrameworkAlternate="netframework-4.0">
<AttributeName Language="C#">[System.Runtime.TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]</AttributeName>
<AttributeName Language="F#">[<System.Runtime.TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")>]</AttributeName>
</Attribute>
</Attributes>
<Parameters />
<Docs>
<summary>Initializes a new instance of the <see cref="T:System.Web.Script.Serialization.JavaScriptTypeResolver" /> class.</summary>
<remarks>To be added.</remarks>
</Docs>
</Member>
<Member MemberName="ResolveType">
<MemberSignature Language="C#" Value="public abstract Type ResolveType (string id);" />
<MemberSignature Language="ILAsm" Value=".method public hidebysig newslot virtual instance class System.Type ResolveType(string id) cil managed" />
<MemberSignature Language="DocId" Value="M:System.Web.Script.Serialization.JavaScriptTypeResolver.ResolveType(System.String)" />
<MemberSignature Language="VB.NET" Value="Public MustOverride Function ResolveType (id As String) As Type" />
<MemberSignature Language="F#" Value="abstract member ResolveType : string -> Type" Usage="javaScriptTypeResolver.ResolveType id" />
<MemberSignature Language="C++ CLI" Value="public:
 abstract Type ^ ResolveType(System::String ^ id);" />
<MemberType>Method</MemberType>
<AssemblyInfo>
<AssemblyName>System.Web.Extensions</AssemblyName>
<AssemblyVersion>3.5.0.0</AssemblyVersion>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
</AssemblyInfo>
<ReturnValue>
<ReturnType>System.Type</ReturnType>
</ReturnValue>
<Parameters>
<Parameter Name="id" Type="System.String" />
</Parameters>
<Docs>
<param name="id">The name of the managed type.</param>
<summary>When overridden in a derived class, returns the <see cref="T:System.Type" /> object that is associated with the specified type name.</summary>
<returns>The <see cref="T:System.Type" /> object that is associated with the specified type name.</returns>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
When a type resolver is associated with a <xref:System.Web.Script.Serialization.JavaScriptSerializer> instance, the serializer uses the <xref:System.Web.Script.Serialization.JavaScriptTypeResolver.ResolveType%2A> method when it iterates through a JSON string to determine the specific managed type to which the JSON type should be converted.
]]></format>
</remarks>
<block subset="none" type="overrides">
<para>Given a string value, the type resolver must return a <see cref="T:System.Type" /> object that represents the corresponding managed type.</para>
</block>
</Docs>
</Member>
<Member MemberName="ResolveTypeId">
<MemberSignature Language="C#" Value="public abstract string ResolveTypeId (Type type);" />
<MemberSignature Language="ILAsm" Value=".method public hidebysig newslot virtual instance string ResolveTypeId(class System.Type type) cil managed" />
<MemberSignature Language="DocId" Value="M:System.Web.Script.Serialization.JavaScriptTypeResolver.ResolveTypeId(System.Type)" />
<MemberSignature Language="VB.NET" Value="Public MustOverride Function ResolveTypeId (type As Type) As String" />
<MemberSignature Language="F#" Value="abstract member ResolveTypeId : Type -> string" Usage="javaScriptTypeResolver.ResolveTypeId type" />
<MemberSignature Language="C++ CLI" Value="public:
 abstract System::String ^ ResolveTypeId(Type ^ type);" />
<MemberType>Method</MemberType>
<AssemblyInfo>
<AssemblyName>System.Web.Extensions</AssemblyName>
<AssemblyVersion>3.5.0.0</AssemblyVersion>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
</AssemblyInfo>
<ReturnValue>
<ReturnType>System.String</ReturnType>
</ReturnValue>
<Parameters>
<Parameter Name="type" Type="System.Type" />
</Parameters>
<Docs>
<param name="type">The managed type to be resolved.</param>
<summary>When overridden in a derived class, returns the type name for the specified <see cref="T:System.Type" /> object.</summary>
<returns>The name of the specified managed type.</returns>
<remarks>
<format type="text/markdown"><![CDATA[
## Remarks
If the <xref:System.Web.Script.Serialization.JavaScriptTypeResolver.ResolveTypeId%2A> method returns either `null` or <xref:System.String.Empty>, then the type resolver does not support the type.
]]></format>
</remarks>
</Docs>
</Member>
</Members>
</Type>