title: WCF Service authorization patterns
body: <p>I'm implementing a secure WCF service. Authentication is done using username / password or Windows credentials. The service is hosted in a Windows Service process. Now, I'm trying to find out the best way to implement <em>authorization</em> for each service operation.</p>
  
  <p>For example, consider the following method:</p>
  
  <pre><code>public EntityInfo GetEntityInfo(string entityId);
  </code></pre>
  
  <p>As you may know, in WCF, there is an OperationContext object from which you can retrieve the security credentials passed in by the caller/client. Now,<em>authentication</em> would have already finished by the time the first line in the method is called. However, how do we implement authorization if the decision depends on the input data itself? For example, in the above case, say 'admin' users(whose permissions etc are stored in a database), are allowed to get entity info, and other users should not be allowed... where do we put the authorization checks?</p>
  
  <p>Say we put it in the first line of the method like so:</p>
  
  <pre><code>CheckAccessPermission(PermissionType.GetEntity, user, entityId) //user is pulled from the current OperationContext
  </code></pre>
  
  <p>Now, there are a couple of questions:</p>
  
  <ol>
  <li><p>Do we validate the entityId (for example check null / empty value etc) BEFORE the authorization check or INSIDE the authorization check? In other words, if authorization checks should be included in every method, is that a good pattern? Which should happen first - argument validation or authorization?</p></li>
  <li><p>How do we unit test a WCF service when authorization checks are all over the place like this, and we don't have an OperationContext in the unit test!? (Assuming I'm tryin to test this service class implementation directly without any of the WCF setup).</p></li>
  </ol>
  
  <p>Any ideas guys?</p>