3

我的授權屬性應用於我的Web API。 我從MVC4應用程序調用Web API,在該應用程序中使用基於標準Cookie的身份驗證。 我需要從集成測試調用控制器上的Web API方法,但因爲應用授權屬性,我總是會收到未經授權的異常如何使用授權屬性進行ASP.NET Web API集成測試

解決此問題的最佳方法是什麼? PS。我不希望(需要)使用其他認證方法,如APIKey,Auth Header中的令牌等。

回答

0

首先,要回答這個問題的一個關鍵要素是要知道什麼樣的您使用的認證機制。

[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); 
} 

當然,你的處理器,其處理認證應該能夠給您的憑證進行身份驗證:例如,如果您使用基本身份驗證,你可以當你的集成測試發送的憑據。

在另一方面,當你將主辦在內存中的應用,經過身份驗證的主要設置爲Thread.CurrentPrincipal將是另一個選擇,但也不會在這裏我最喜歡的選項。

+0

感謝您的回答,但我已經指出,我正在使用ASP.NET MVC 4登錄功能,這意味着我登錄到ASP.NET MVC 4網站,並且當我向WebAPI請求時,Authorize屬性將授予我因爲我在該請求中發送授權cookie。 –

+0

現在所有的身份驗證都在ASP.NET MVC 4中,因爲它在同一個項目中是一個WebAPI。現在我不需要WebAPI內部的自定義基本認證。 –

+1

@RadenkoZec我假設你正在做表單身份驗證。因此,刪除我的示例上面的授權標題,並將表單auth cookie放到請求中。這個想法是一樣的。我的例子只是給你一個提示。 – tugberk