0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

this might explain the constant "internalservererror" I kept getting. I'll just rely on postman. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.