Read user claims information in SharePoint 2013

In this article, we will see how to read user claims in SharePoint 2013. For this I have prepared one httphandler, which will read the claims information of current logged in user (authentication type windows, forms or third party trusted provider).

using Microsoft.IdentityModel.Claims;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration.Claims;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace SSONamespace
{
    class SSOAuthenticationExample : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
        }

        void context_PreRequestHandlerExecute(object sender, EventArgs e)
        {            
            string requestUrl = HttpContext.Current.Request.Url.ToString();
            IClaimsIdentity ci = (IClaimsIdentity)HttpContext.Current.User.Identity;
            List<Claim> claimCollection = ci.Claims.OfType<Claim>().Select(x => x).ToList();

	/*Uncomment these lines to see all claims entries */
            //string text = string.Empty;
            //foreach (Claim item in ci.Claims)
            //{
            //    text += item.ClaimType + " : " + item.Value + " | ";
            //}

            //System.IO.File.WriteAllText(@"C:\SSOClaims.txt", text);
		
		//fetch information from claims
            string userName = claimCollection.Where(x => x.ClaimType.ToLower().Contains("userid")).Select(y => y.Value).FirstOrDefault();
         }

        public void Dispose() { }

    }
}

Now deploy this code and add below entry in web.config file of web application :

<system.web>
  <httpModules>
    <add name="SSONamespaceModule" type="SSONamespace.SSOAuthenticationExample , SSONamespace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3af8d8e2f9e8b6c3"  precondition="integratedmode" />
  </httpModules>
</system.web>

Note : Replace PublicKeyToken value from your own project’s PublicKeyToken

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s