سؤال

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.

هل كانت مفيدة؟

المحلول 2

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.

نصائح أخرى

What does your Authorize attribute do when it performs the authorization check? There are quite a few options that come to mind:

  • Have the authorize filter support multiple means of getting the "authorization token" that it requires (e.g. through an HTTP header or a querystring parameter, etc)
  • Right after your test initialization, clear out the filter from the configuration (so that it is not called at all). If you choose to go this route then you may wish to pop in a new filter that sets any authorization values that might be used further along the pipeline
  • If you are using dependency injection, move the "authorization check" into some sort of IAuthorize location that can be updated in your configuration

I would also recommend using RestSharp for making queries to your endpoints as it does a very good job of specifying headers, parameters, etc.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top