In the previous posts I talked about claims and claim sets. Now how do you use claim sets for authorization?
Let’s take WCF as an example. In WCF you get access to the system generated claim sets via the AuthorizationContext (I have not yet explained where the AuthorizationContext comes from and how it is created – but I will in a future post). The typical code you write to access claim sets would be:
IEnumerable<ClaimSet> claimSets =
ServiceSecurityContext.Current.AuthorizationContext.ClaimSets;
Once you have access to the claim sets you typically do the following operations:
- Check if a specified claim is in one of the claim sets
- Search for occurrences of a specified claim type in the claim sets
In addition you also want to specify the issuer of the claim you are looking for, e.g. search for the Name claim issued by ‘System’ or ‘Windows’.
Unfortunately this simple task is a little cumbersome to achieve. Since you only have the FindClaim and ContainsClaim methods on ClaimSet itself, but not on the claim set list, you’d have to do this:
- Cycle through all the claim sets and inspect the issuer.
- If the issuer matches the one you are looking for use the issued claim set
- Search the claim set for the claim you are looking for
Extension methods to the rescue. In LeastPrivilege.IdentityModel I have extended IEnumerable<ClaimSet> with search operations that work across a list of claim sets:
- ContainsClaim
- FindClaim(s)
- FindIdentityClaim
- GetClaimSetsByIssuer
All these operations let you specify an issuer claim (or claim set) and the various overloads also allow to specify a claim comparer or if you want to search in issuer or issued claims.
The following code would achieve the above task (searching for the Windows account name):
Claim name = claimSets.FindClaim(ClaimTypes.Name, ClaimSet.Windows);
To get the Windows SID identity claim issued to the user, you could do this:
Claim sid = claimSets.FindIdentityClaim(ClaimSet.Windows);
…or directly convert to a SecurityIdentifier:
SecurityIdentifier sid =
claimSets.FindIdentityClaim(ClaimSet.Windows).Get<SecurityIdentifier>();
This makes working with claim sets a little easier. In the next posts I will talk about how to create an AuthorizationContext yourself (e.g. to use the same programming model outside of WCF) and how authorization policies come mix in here.