DoesUserHavePermission() with classic and claims based authentication mixed

Recently I had to check the current user’s permissions to access some predefined links in SharePoint 2010 generally using classic authentication. Usually, DoesUserHavePermission() has the answer. But for links pointing into an application with claims based authentication it would always return false. Solved it by prefixing the user’s LoginName with an identity token – for Windows authentication in this case. Calling SPWeb.EnsureUser() and using the resulting SPUser’s LoginName should also do the trick.

private bool HasCurrentUserReadPermission(string absoluteUrl)
{
   bool result = false;
   string loginName = SPContext.Current.Web.CurrentUser.LoginName;
   SPSecurity.RunWithElevatedPrivileges(delegate() {
      try {
         using (SPSite site = new SPSite(absoluteUrl)) {
            using (SPWeb web = site.OpenWeb()) {
               if (site.WebApplication.UseClaimsAuthentication) {
                  // convert login to identity claim
                  // e. g. DOMAIN\user_name -> i:0#.w|domain\user_name
                  loginName = "i:0#.w|" + loginName.ToLower();
               }
               result = web.DoesUserHavePermissions(
                  loginName, SPBasePermissions.ViewPages);
            }
         }
      }
      catch (Exception x) {
         // log exception
      }
   });
   return result;
}

On a more general note: to use RunWithElevatedPrivileges() on sites running in a different application pool, the application pool’s accounts need to match. Of course this defeats one of the main purposes for using multiple application pools in the first place.

External References

Advertisements
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

One Response to DoesUserHavePermission() with classic and claims based authentication mixed

  1. Steve says:

    You should not be using the string literal to prefix the login name, encode as follows:

    string userClaim = null;
    SPClaimProviderManager claimMgr = SPClaimProviderManager.Local;
    if (claimMgr != null)
    {
    SPClaim claim = new SPClaim(SPClaimTypes.UserLogonName, “ceej”, ClaimValueTypes.String, SPOriginalIssuers.Format(SPOriginalIssuerType.Forms, “3guysmembership”));
    userClaim = claimMgr.EncodeClaim(claim);
    }

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