Skip to content

Commit 0ada833

Browse files
Support round trip serialization of AuthenticationProperties with System.Text.Json (#31330) #20722
1 parent 2488cce commit 0ada833

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

src/Http/Authentication.Abstractions/src/AuthenticationProperties.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System;
55
using System.Collections.Generic;
66
using System.Globalization;
7+
using System.Text.Json.Serialization;
78

89
namespace Microsoft.AspNetCore.Authentication
910
{
@@ -30,6 +31,7 @@ public AuthenticationProperties()
3031
/// Initializes a new instance of the <see cref="AuthenticationProperties"/> class.
3132
/// </summary>
3233
/// <param name="items">State values dictionary to use.</param>
34+
[JsonConstructor]
3335
public AuthenticationProperties(IDictionary<string, string?> items)
3436
: this(items, parameters: null)
3537
{ }

src/Http/Authentication.Core/test/AuthenticationPropertiesTests.cs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
using System.Collections.Generic;
33
using System.Globalization;
44
using System.Linq;
5+
using System.Text.Json;
56
using Xunit;
67

78
namespace Microsoft.AspNetCore.Authentication.Core.Test
@@ -302,6 +303,42 @@ public void GetBool()
302303
Assert.Equal("BAR", props.Items["foo"]);
303304
}
304305

306+
[Fact]
307+
public void Roundtrip_Serializes_With_SystemTextJson()
308+
{
309+
var props = new AuthenticationProperties()
310+
{
311+
AllowRefresh = true,
312+
ExpiresUtc = new DateTimeOffset(2021, 03, 28, 13, 47, 00, TimeSpan.Zero),
313+
IssuedUtc = new DateTimeOffset(2021, 03, 28, 12, 47, 00, TimeSpan.Zero),
314+
IsPersistent = true,
315+
RedirectUri = "/foo/bar"
316+
};
317+
318+
props.Items.Add("foo", "bar");
319+
320+
props.Parameters.Add("baz", "quux");
321+
322+
var json = JsonSerializer.Serialize(props);
323+
var deserialized = JsonSerializer.Deserialize<AuthenticationProperties>(json);
324+
325+
Assert.NotNull(deserialized);
326+
327+
Assert.Equal(props.AllowRefresh, deserialized!.AllowRefresh);
328+
Assert.Equal(props.ExpiresUtc, deserialized.ExpiresUtc);
329+
Assert.Equal(props.IssuedUtc, deserialized.IssuedUtc);
330+
Assert.Equal(props.IsPersistent, deserialized.IsPersistent);
331+
Assert.Equal(props.RedirectUri, deserialized.RedirectUri);
332+
333+
Assert.NotNull(deserialized.Items);
334+
Assert.True(deserialized.Items.ContainsKey("foo"));
335+
Assert.Equal(props.Items["foo"], deserialized.Items["foo"]);
336+
337+
// Ensure that parameters are not round-tripped
338+
Assert.NotNull(deserialized.Parameters);
339+
Assert.Equal(0, deserialized.Parameters.Count);
340+
}
341+
305342
public class MyAuthenticationProperties : AuthenticationProperties
306343
{
307344
public new DateTimeOffset? GetDateTimeOffset(string key)

0 commit comments

Comments
 (0)