如何做到与授权属性的ASP.NET Web API集成测试 [英] How to do ASP.NET Web API integration tests with authorize attribute

查看:250
本文介绍了如何做到与授权属性的ASP.NET Web API集成测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有应用在我的Web API授权属性。
我打电话从里面我是用标准的基于Cookie的身份验证MVC4应用程序的Web API。
我需要调用从集成测试控制器的Web API的方法,但由于授权属性应用于我会一直收到的未经授权的例外

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.

什么是解决这个问题的最好方法是什么?
PS。我不想(需要)使用身份验证的其他方法,如APIKey,令牌在验证页眉和类似...

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...

推荐答案

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

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.

这篇关于如何做到与授权属性的ASP.NET Web API集成测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆