且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何做到与授权属性的ASP.NET Web API集成测试

更新时间:2023-02-17 12:58:47

首先,为了回答这个问题的一个关键因素是要知道你用什么样的认证机制。例如,如果您使用基本身份验证,您可以发送凭据,当你的集成测试:

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.

在另一方面,当你将主办在内存中的应用程序,设置身份验证的校长到 Thread.CurrentPrincipal中则是另一种选择,但不会是我的喜欢的选择在这里。

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.