Many of you may know that SharePoint 2010 comes equipped with support for Claims-Based Authentication. For an in-depth description of what Claims-Based Authentication is and how it can be utilized in SharePoint, please see TechNet or MSDN (there is a lot of good content out there that can get you up to speed).

Adding Claims through the SharePoint user interface is pretty straightforward and is very similar to how you add users or groups in a traditional SharePoint setting. However, when adding claims using code, there are a few extra steps and a few new objects to be aware of when compared to non-claims based scenarios.

The trickiest part of assigning a claim to a securable object is getting the claim moniker in the correct format. Fortunately, there is a helper method on the SPClaim object assist with that (ToEncodedString). But first thing’s first: We have to create the claim.

To do that, we have to know a few things about the claim we want to assign, its type, value, value type and original issuer. You can read online to get more detail on what those items are and how to find them, but once specified in the constructor of the SPClaim object, we have a claim to encode.

Once you have successfully called the ToEncodedString method of the SPClaim object, the hard part is done. From there we can assign that string to any SPRoleAssignment object just like we would a username.

The code below gives you a snippet that you can use anywhere, so long as you replace the literal values appropriately.

SPClaim c = new SPClaim(“http://www.sp911.com/claims/customer”,
                        “CompanyXYZ_Read”,
                        ClaimValueTypes.String,
                        SPOriginalIssuers.Format(
                            SPOriginalIssuerType.TrustedProvider,
                            “My Claims Provider Name”)
                        );

string encodedClaim = c.ToEncodedString();

using (SPSite siteCollection = new SPSite(“http://www.sp911.com”))
using (SPWeb site = siteCollection.OpenWeb())
{
    SPRoleAssignment roleAssignment = new SPRoleAssignment(encodedClaim,
                                                           null,
                                                           “NameForClaim”,
                                                           null);

    roleAssignment.RoleDefinitionBindings.Add(site.RoleDefinitions[“Read”]);
    site.Lists[“Documents”].RoleAssignments.Add(roleAssignment);
    site.Lists[“Documents”].Update();
}

Larry Riemann is a consultant with SharePoint911.