How to do ASP.NET Web API integration tests with a

2019-04-10 01:23发布

I do have authorize attribute applied on my Web API. I am calling Web API from MVC4 application in which I am using standard cookie based authentication. I need to call Web API method on controllers from integration tests but because authorize attribute is applied I will always receive unauthorized exception.

What is the best way to solve this problem ? PS. I don't want (need) to use other methods of authentication such as APIKey,Token in Auth Header and similar...

1条回答
我命由我不由天
2楼-- · 2019-04-10 02:18

First of all, one key element in order to answer this question is to know what kind of authentication mechanism you use. For example, if you use basic auth, you can send the credentials when you are integration testing:

[Fact]
public async Task FooTest() { 

    var username = "user";
    var password = "supersecret";

    // construct your config here as I do below.
    // RouteConfig and WebAPIConfig are my own classes
    var config = new HttpConfiguration();
    RouteConfig.RegisterRoutes(config);
    WebAPIConfig.Configure(config);

    var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/api/cars");
    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    request.Headers.Authorization = new AuthenticationHeaderValue(
        "Basic", EncodeToBase64(string.Format("{0}:{1}", username, password)));

    using (var httpServer = new HttpServer(config))
    using (var client = new HttpClient(httpServer)) {

        var response = await client.SendAsync(request);
        var result = await response.Content.ReadAsAsync<Car>();

        // do you test now...
    }
}

private static string EncodeToBase64(string value) {

    byte[] toEncodeAsBytes = Encoding.UTF8.GetBytes(value);
    return Convert.ToBase64String(toEncodeAsBytes);
}

Of course, your handler which handles the authentication should be able to authenticate you with those credentials.

On the other hand, as you will be hosting the application in memory, setting an authenticated principal to the Thread.CurrentPrincipal would be another option but wouldn't be my favorite option here.

查看更多
登录 后发表回答