Get ClaimsIdentity not GenericIdentity in a WCF service

Posted on 2/24/2014 @ 5:09 AM in #WCF by | Feedback | 1348 views

A common issue you may run into, inside SharePoint or not SharePoint, is when authoring a WCF service running under WIF auth, even if you specify ASPNET compatibility mode = allowed or required,

  • your HttpContext.Current.User is null,
  • OperationContext.Current is null
  • System.Threading.Thread.CurrentPrincipal is of type GenericPrincipal

Worry not, there are just a few minor tweaks you need to make and you’ll be on the road again.

#1. author a Service Host Factory, like this -

   1:      public class MyServiceHostFactory : ServiceHostFactory
   2:      {
   3:          public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
   4:          {
   5:              ServiceHostBase host = base.CreateServiceHost(constructorString, baseAddresses);
   6:              host.Authorization.ServiceAuthorizationManager = new ODataAuthorizationManager();
   7:              FederatedServiceCredentials.ConfigureServiceHost(host);
   8:              return host;
   9:          }
  10:      }

#2. Create the Authorization manager (I’m authorizing all, you may want to do something fancier) -

   1:      public class ODataAuthorizationManager : IdentityModelServiceAuthorizationManager
   2:      {
   3:          public ODataAuthorizationManager()
   4:          {
   5:          }
   6:   
   7:          protected override bool CheckAccessCore(OperationContext operationContext)
   8:          {
   9:              return true;
  10:          }
  11:      }

 

#3. Author the following service behavior in the web.config and make sure you tie it in your service config:

   1:          <behavior name="IdentityBehavior">
   2:            <serviceAuthorization principalPermissionMode="Always" serviceAuthorizationManagerType="yournamespace.ODataAuthorizationManager, yourdll" />
   3:          </behavior>

 

That’s it! F5 and enjoy the fruits of your labor.

Sound off but keep it civil:

Older comments..