Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store array of int into claims with AddClaims

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

like image 875
Philippe Auriou Avatar asked Oct 20 '25 21:10

Philippe Auriou


2 Answers

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);
like image 87
DemoBytom Avatar answered Oct 22 '25 11:10

DemoBytom


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.

like image 38
Markus Avatar answered Oct 22 '25 13:10

Markus