Search code examples
wcfweb-serviceswcf-bindingwcf-securityrestful-authentication

RESTful WCF service security


How we could authenticate/authorize WCF RESTful service (that uses webHttpBinding (and not wsHttpBinding, like in SOAP case))? I.e. we want to use Membership/Roles to permit (or prohibit) user consume each web method according his role.

Thanks in advance. Ilan.


Solution

  • You can use certificates to secure the service or send the username and password in the header. You can then add a behavior by implementing IAuthorizationPolicy to the service so that you don't have to implement the security check in every web service method that you expose.

    public class CertificateAuthorizationPolicy : IAuthorizationPolicy
    {
    
        public bool Evaluate(EvaluationContext evaluationContext, ref object state)
        {
            IIdentity identity;
            object untypedIdentities;
            if (!evaluationContext.Properties.TryGetValue("Identities", out untypedIdentities))
            {
                identity = null;
                return false;                                                                                                             
            }
    
            var identities = (IEnumerable<IIdentity>)untypedIdentities;
    
            identity = identities.Where(item => item.AuthenticationType == "X509").FirstOrDefault();
    
            var claimSet = (X509CertificateClaimSet)evaluationContext.ClaimSets[0];
            var certificate = claimSet.X509Certificate;
    
        }
    

    In web.config you tell the service to use the authorization policy

        <behavior name="CertificateSecurityServiceBehavior">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" />
          <serviceDebug includeExceptionDetailInFaults="true" />
          <serviceAuthorization principalPermissionMode="Custom">
            <authorizationPolicies>
              <add policyType="CertificateAuthorizationPolicy, MyAssembly.Security" />
            </authorizationPolicies>
          </serviceAuthorization>
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
        </behavior>
    

    Another option is to setup SSL on the IIS Server so that it requires SSL and client certificate to connect to any page.