Gustav Bertram
Gustav Bertram

Reputation: 14901

How can I use a Unit Test to test my API's authentication and authorization?

A colleague wrote an HTTP API. He implemented the security using a DelegatingHandler that implements basic HTTP authorization.

He added a route config to apply the BasicAuthHandler to the API route in a global config:

config.Routes.MapHttpRoute(
    name: "Api",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional },
    constraints: null,
    handler: BasicAuthHandler
);

I wrote a unit test to test the API call:

[TestClass]
public class ApiControllerTest
{
  private ApiRepository repo = new ApiTestRepository();

  [TestMethod]
  public void Get()
  {
    // Arrange
    var config = new HttpConfiguration();
    var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/api/driver/1");
    var route = config.Routes.MapHttpRoute("Default", "api/{controller}/{id}");

    ApiDriverController controller = new ApiDriverController(repo)
    {
      Request = request,
    };

    controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;

    // Act
    var Results = controller.Get(1);

    // Assert
    // ...
  }
}

When I use a browser to call the API, it does have security. However, the API test doesn't seem to require it.

Is there a reason the API test works when it shouldn't? Is there a way I can test the security?

Upvotes: 0

Views: 1420

Answers (1)

Kenneth
Kenneth

Reputation: 28737

The reason is that when you test the application through a browser, your website runs inside IIS. It's IIS that creates the pipeline and routes the request through all the handlers.

When you unit test your application, it's running inside your unit test context (as an ordinary assembly). That means that there's no pipeline and the modules are not loaded as they would in IIS.

The only thing you can do to prevent this is to create an integration test and test the app from the outside

Upvotes: 1

Related Questions