Handle `null`s in the `JsonDocumentAuthExtensions.GetString` extension method (#10252)
This commit is contained in:
parent
dc90e11c7a
commit
9f4aa98ee2
|
|
@ -7,8 +7,14 @@ namespace Microsoft.AspNetCore.Authentication
|
|||
{
|
||||
public static class JsonDocumentAuthExtensions
|
||||
{
|
||||
public static string GetString(this JsonElement element, string key) =>
|
||||
element.TryGetProperty(key, out var property)
|
||||
? property.ToString() : null;
|
||||
public static string GetString(this JsonElement element, string key)
|
||||
{
|
||||
if (element.TryGetProperty(key, out var property) && property.Type != JsonValueType.Null)
|
||||
{
|
||||
return property.ToString();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,15 +27,7 @@ namespace Microsoft.AspNetCore.Authentication.MicrosoftAccount
|
|||
ClaimActions.MapJsonKey(ClaimTypes.Name, "displayName");
|
||||
ClaimActions.MapJsonKey(ClaimTypes.GivenName, "givenName");
|
||||
ClaimActions.MapJsonKey(ClaimTypes.Surname, "surname");
|
||||
ClaimActions.MapCustomJson(ClaimTypes.Email, user =>
|
||||
{
|
||||
var mail = user.GetString("mail");
|
||||
if (string.IsNullOrEmpty(mail))
|
||||
{
|
||||
mail = user.GetString("userPrincipalName");
|
||||
}
|
||||
return mail;
|
||||
});
|
||||
ClaimActions.MapCustomJson(ClaimTypes.Email, user => user.GetString("mail") ?? user.GetString("userPrincipalName"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,26 @@
|
|||
// Copyright (c) .NET Foundation. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
|
||||
|
||||
using System.Text.Json;
|
||||
using Xunit;
|
||||
|
||||
namespace Microsoft.AspNetCore.Authentication.Test
|
||||
{
|
||||
public class JsonDocumentAuthExtensionsTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("{ \"foo\": null }", null)]
|
||||
[InlineData("{ \"foo\": \"\" }", "")]
|
||||
[InlineData("{ \"foo\": \"bar\" }", "bar")]
|
||||
[InlineData("{ \"foo\": 1 }", "1")]
|
||||
[InlineData("{ \"bar\": \"baz\" }", null)]
|
||||
public void GetStringReturnsCorrectValue(string json, string expected)
|
||||
{
|
||||
using (var document = JsonDocument.Parse(json))
|
||||
{
|
||||
var value = document.RootElement.GetString("foo");
|
||||
Assert.Equal(expected, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -203,8 +203,7 @@ namespace Microsoft.AspNetCore.Authentication.Tests.MicrosoftAccount
|
|||
displayName = "Test Name",
|
||||
givenName = "Test Given Name",
|
||||
surname = "Test Family Name",
|
||||
mail = "",
|
||||
userPrincipalName = "Test email"
|
||||
mail = "Test email"
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue