I'm developing a web app with Asp.Net 5 MVC, Owin and Oauth2 bearer token as auth type.
I need to store a list of string "CODEFOO,CODBAR,CODEX,.."
inside a System.Security.Claims.Claim with a custom claim Type.
When the user requests a token, this list of "user codes" is get from the back-end and set inside the identity using a specific custom claim type.
When the user sends the token back, navigating a specific MVC Action, the application has to check if the list of user codes inside the claim, contains a specific code.
List<string> userCodes = rep.GetUserCodeFromBackEnd();
string userCodesClaimType = "http://foo.it/claim/usercodesclaimtype";
Right now I'm serializing the list of string in JSON.
var claim = new Claim(userCodesCaimType, JsonConvert.SerializeObject(userCodes));
and get it back de-serializing it with something like this:
var userCodesClaim = identity.Claims.FirstOrDefault<Claim>(c=>c.Type == userCodesClaimType) ;
var userCodesClaimValue = JsonConvert.DeserializeObject<List<string>>(userCodesClaim.Value);
Now the question:
is there a better way to store a list of values inside a claim?
Claim has a ValueType property which documentation says:
The ValueType property contains a string that identifies the type information of the value. This property can be used to understand the format of the value and to provide information about how to serialize and deserialize the value. If your solution requires complex value types, it is recommended that you use standard XML schema types in the ValueType property to indicate how the Value property is meant to be serialized and deserialized from a string.
Unluckily I have not found any example that documents the use of that property.
Is the Json serialization ok or should I use the ValueType approach?
The ValueType
is a way for your code to identify how the value is to be interpreted/deserialized, such as containing an XML schema type. If used between code from different sources, it makes sense, but in your own application you can just ignore it as long as you know how to interpret the contents.
But to have multiple values, you won't need to use complex types. A claims identity can have multiple claims with the same ClaimType
, so instead of serializing the codes into a JSon string you should just add multiple claims; one for each user code. All having the same claim type. That will make it possible to use the HasClaim
method for checking if a specific user code is present.