Skip to content

Commit

Permalink
Support roundtrip serialization with S.T.Json
Browse files Browse the repository at this point in the history
Add attribute to support round-trip serialization of AuthenticationProperties with System.Text.Json.
Resolves dotnet#20722.
  • Loading branch information
martincostello committed Mar 28, 2021
1 parent 7dea0cb commit bf81ce3
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.Json.Serialization;

namespace Microsoft.AspNetCore.Authentication
{
Expand All @@ -30,6 +31,7 @@ public AuthenticationProperties()
/// Initializes a new instance of the <see cref="AuthenticationProperties"/> class.
/// </summary>
/// <param name="items">State values dictionary to use.</param>
[JsonConstructor]
public AuthenticationProperties(IDictionary<string, string?> items)
: this(items, parameters: null)
{ }
Expand Down
36 changes: 36 additions & 0 deletions src/Http/Authentication.Core/test/AuthenticationPropertiesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.Json;
using Xunit;

namespace Microsoft.AspNetCore.Authentication.Core.Test
Expand Down Expand Up @@ -302,6 +303,41 @@ public void GetBool()
Assert.Equal("BAR", props.Items["foo"]);
}

[Fact]
public void Roundtrip_Serializes_With_SystemTextJson()
{
var props = new AuthenticationProperties()
{
AllowRefresh = true,
ExpiresUtc = new DateTimeOffset(2021, 03, 28, 13, 47, 00, TimeSpan.Zero),
IssuedUtc = new DateTimeOffset(2021, 03, 28, 12, 47, 00, TimeSpan.Zero),
IsPersistent = true,
RedirectUri = "/foo/bar"
};

props.Items.Add("foo", "bar");

props.Parameters.Add("baz", "quux");

var json = JsonSerializer.Serialize(props);
props = JsonSerializer.Deserialize<AuthenticationProperties>(json);

Assert.NotNull(props);

Assert.True(props!.AllowRefresh);
Assert.Equal(new DateTimeOffset(2021, 03, 28, 13, 47, 00, TimeSpan.Zero), props.ExpiresUtc);
Assert.Equal(new DateTimeOffset(2021, 03, 28, 12, 47, 00, TimeSpan.Zero), props.IssuedUtc);
Assert.True(props.IsPersistent);
Assert.Equal("/foo/bar", props.RedirectUri);

Assert.NotNull(props.Items);
Assert.True(props.Items.ContainsKey("foo"));
Assert.Equal("bar", props.Items["foo"]);

Assert.NotNull(props.Parameters);
Assert.Equal(0, props.Parameters.Count);
}

public class MyAuthenticationProperties : AuthenticationProperties
{
public new DateTimeOffset? GetDateTimeOffset(string key)
Expand Down

0 comments on commit bf81ce3

Please sign in to comment.