title: Unit Testing a custom Web API AuthorizeAttribute
body: <p>I am trying to unit test, with NUnit in C#, a custom Authorize Attribute. In particular that a particular http status code and message have been returned in the case of not being authorized. </p>
  
  <p>My attribute is super simple - looks like this:</p>
  
  <pre><code>public class AuthorizationAttribute : AuthorizeAttribute
  {
  
      public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
      {
          if (IsAuthorized(actionContext))
              return;
  
          HandleUnauthorizedRequest(actionContext);
      }
  
      protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
      {
          actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Forbidden, "You are not authorized to access this resource");
      }
  }
  </code></pre>
  
  <p>So to test this (and currently new in the field of testing) I have cobbled together the following code. In it, i am attaching a generic identity with a username and some role data.</p>
  
  <pre><code>public void Given_UserIsNotInAuthorizedRoles_When_Auhtorizing_ReturnsForbidden()
  {
  
      // Arrange
  
      IPrincipal principal = new GenericPrincipal(new GenericIdentity("TestName"), new[] { "TestRole" });
  
      HttpActionContext mockActionContext = new HttpActionContext()
      {
          ControllerContext = new HttpControllerContext()
          {
              Request = new HttpRequestMessage(),
              RequestContext = new HttpRequestContext() { Principal = principal }
          },
          ActionArguments = { { "SomeArgument", "null" } }
      };
  
      mockActionContext.ControllerContext.Configuration = new HttpConfiguration();
      mockActionContext.ControllerContext.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
  
      // Act
      AuthorizationAttribute authAttr = new AuthorizationAttribute();
      authAttr.OnAuthorization(mockActionContext);
  
      // Assert
      Assert.IsTrue(mockActionContext.Response.StatusCode == System.Net.HttpStatusCode.Forbidden);
  
  }
  </code></pre>
  
  <p>The mock controller looks like this:    </p>
  
  <pre><code>[Authorization(Roles = "AdminRoleOnly", Users = "A user")]
  internal class MockController : ApiController { }
  </code></pre>
  
  <p>When I'm debugging, i am finding that <code>if (IsAuthorized(actionContext))</code> is returning <code>true</code> - which i don't understand. </p>
  
  <p>Can someone point me in the direction of why my authorize attribute is passing this identity as good?</p>
  
  <p>For what it's worth, this code works in production. I'm back-filling some tests.</p>
  
  <hr>
  
  <p>Somewhat related, are these ones</p>
  
  <p>I've read through the question and answer on a similar question <a href="https://stackoverflow.com/questions/18701433/asp-net-mvc-unit-testing-custom-authorizeattribute">ASP.NET MVC unit testing custom AuthorizeAttribute</a> though neither really either work nor relate, especially given they're for MVC controllers and not Api Controllers. </p>
  
  <p>I've also read and tried to implement the code in the answer on this question too <a href="https://stackoverflow.com/questions/17230081/mocking-httpactioncontext-actionarguments-when-testing-web-api-actionfilter">Mocking HttpActionContext.ActionArguments when testing Web.Api ActionFilter</a></p>
  
  <hr>
  
  <p>The latter gets me somewhere near in that my authorization attribute is firing in a test and I am able to pass in the required context information.</p>