Wednesday, June 20, 2012

Capturing Web Analytics Data in a Custom Web Part



The problem:

I need to display the number of daily unique visitors to a site collection on a custom web part. Using the following code results in an array with the only element being "The specified user or domain was not found." The Web application uses claims authentication.


The solution:

What is causing this issue?

The problem is that the GetWebAnalyticsReportData() function takes the user login name from Thread.CurrentPrincipal.Identity.Name and passes it to SPWeb.DoesUserHavePermissions() - but SPSecurity.RunWithElevatedPrivileges does not change Thread.CurrentPrincipal.Identity.Name to the application pool account name. It does, however, change WindowsIdentity.GetCurrent() to the application pool account.

So, it is necessary to explicitly set Thread.CurrentPrincipal to the correct identity. Since my Web application uses claims authentication, here is a correct way to do this:

System.Threading.Thread.CurrentPrincipal = 
 ClaimsPrincipal.CreateFromIdentity(WindowsIdentity.GetCurrent());

Works like a charm!

2 comments: