I want to put an array of int in one of my claims on a web application .net core 2.2.
When logging in to create the ticket I use this to add claims, but how to add a complex object.
if (ticket.HasScope(OpenIdConnectConstants.Scopes.Profile))
{
if (!string.IsNullOrWhiteSpace(user.FirstName))
identity.AddClaim(CustomClaimTypes.FirstName, user.FirstName, OpenIdConnectConstants.Destinations.IdentityToken);
if (!string.IsNullOrWhiteSpace(user.LastName))
identity.AddClaim(CustomClaimTypes.LastName, user.LastName, OpenIdConnectConstants.Destinations.IdentityToken);
if (user.Functions.Any())
// not possible : Functions = List<int>
identity.AddClaim(CustomClaimTypes.Functions, user.Functions, OpenIdConnectConstants.Destinations.IdentityToken);
}
With AddClaims, it is only possible to add strings
You can serialize a complex object into a json and then add it to the claim. Something along the lines of:
identity.AddClaim(ClaimName, JsonConvert.SerializeObject(intArray));
And then upon read just deserialize it back:
int[] intArray = JsonConvert.DeserializeObject<int[]>(claim.Value);
You can add the same claim type repeatedly, e.g.:
foreach(var f in user.Functions)
identity.AddClaim(CustomClaimTypes.Functions, f.ToString(), OpenIdConnectConstants.Destinations.IdentityToken);
As an alternative, you could join the integers and split them after accessing the claim:
if (user.Functions.Any())
{
var joinedFunctions = string.Join(";", user.Functions);
identity.AddClaim(CustomClaimTypes.Functions, joinedFunctions, OpenIdConnectConstants.Destinations.IdentityToken);
}
To retrieve the values you can split them afterwards:
functionsClaimValue.split(';');
You need to make sure that the separator you choose (in this sample a semicolon) cannot be contained as a regular character in the values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With