Skip to main content

Cloud

How To Create a Claims Viewer Web Part for SharePoint 2010

For the past month or so I’ve been giving Windows Identity Foundation a very close look, especially where it relates to SharePoint 2010. I’ll be posting a series of blogs on this subject and I thought it might be useful to start off with a quick introduction on how to access the claims from which an SPUser object is derived. I feel this is very helpful for folks who are looking to learn more about that what this stuff is all about. As they say, seeing is believing!
The good news is this is fairly easy to do since the SharePoint development tools provided in Visual Studio 2010 do all the heavy lifting for you with respect to solution creation and deployment. By now, I’m sure you’re already aware of this so I won’t spend much time on these features. For this article, I’m assuming you’ll be creating this web part on a development server (or virtual machine) that has both Visual Studio 2010 and SharePoint 2010 installed.
You start by creating a new project with the Visual Web Part template. Feel free to name the solution whatever you wish.
image
Using the split or design view, drag and drop a GridView control onto the .ascx page. In this example, I’ll just use the default name of “GridView1”.
Next, switch to the code-behind for the user control and add a reference to Microsoft.IdentityModel. IMPORTANT: If you have multiple versions of this .dll installed, be sure to reference version 1.0.0.0. This is the version SharePoint 2010 uses and therefore the version we must use.
Add the following code to the user control (.ascx.cs ). Its based on a sample provided on this MSDN blog a while back.

Code Snippet
  1. using System;
  2. using System.Web.UI;
  3. using System.Web.UI.WebControls;
  4. using System.Web.UI.WebControls.WebParts;
  5. using Microsoft.IdentityModel.Claims;
  6. namespace ClaimsViewerTest.VisualWebPart1
  7. {
  8. public partial class VisualWebPart1UserControl : UserControl
  9. {
  10. protected void Page_Load(object sender, EventArgs e)
  11. {
  12. IClaimsPrincipal claimsPrincipal = Page.User as IClaimsPrincipal;
  13. IClaimsIdentity claimsIdentity = (IClaimsIdentity)claimsPrincipal.Identity;
  14. GridView1.DataSource = claimsIdentity.Claims;
  15. Page.DataBind();
  16. }
  17. }
  18. }

Lines 16 and 17 bind the claims data to the grid view control. Next, simply hit F5 to deploy and debug. Once you’re satisfied the web part is functional, I recommend adding it to the default page of a site collection within a claims-enabled web application. When signing in, you’ll see something like the following:
image
That’s it!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Travis Nielsen

More from this Author

Follow Us
TwitterLinkedinFacebookYoutubeInstagram