Q:

Testing WebAPI actions that have authorization filters

I’ve got a Web API that I’ve added [Authorize] attributes to, which means that the unit tests I had previously now fail due to them being unauthorised. Here’s a sample of a basic test along with an initialiser method:
[TestInitialize]
public void CreateServer() {
    var config = new HttpConfiguration();
    WebApiConfig.Configure(config); // Create the routes
    var server = new HttpServer(config);
    this.client = new HttpClient(server);
}

[TestMethod]
public void MyThings_GET_Returns_All_MyThings() {
    var response = this.client.GetAsync("http://localhost/api/1.0/mythings").Result;

    var mythings = response.Content.ReadAsAsync<IEnumerable<MyThing>>().Result;

    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
    Assert.AreEqual(4, mythings.Count());
}

What I’m wondering is if there’s any way that I can either make my test log in so that it passes the authorization filter, or if there’s any way that I can pass as ASPXAUTH cookie along with the HttpClient request? Or another way of passing authorization that I haven’t thought of?
Nothing I’ve tried seems to work and I’m struggling to find any helpful info anywhere.
Thanks in advance.

A:

I decided that the way I was going about the problem was fundamentally wrong. Using cookie-based authorisation with Web API is just not a good idea, so I’ve decided to get rid of the authorize attributes and perform API-Key-based authentication instead. This makes it easier to test as I can just pass the correct API key in the request, but also means that I’m not relying on cookies for authorisation.

