测试受 [Authorize] 保护的 Web API 控制器

Testing Web API controllers protected with [Authorize]

我刚刚使用 ASP.net 身份 OWIN 和 OAuth 2 向我的 Web API 添加了基于令牌的安全性。因此,我在所有测试中都遇到了 405 未经授权的错误。我怎样才能模拟安全上下文。我看过一些示例,其中其他示例覆盖了 Thread.CurrentPrincipal 但不确定这是否是正确的方法。

样本测试

    [TestMethod]
    public void Verify_GetReferenceData_Http_Get()
    {
        var configAE = new HttpSelfHostConfiguration("http://localhost:53224");
        Konstrukt.SL.AggregationEngine.WebApiConfig.Register(configAE, new AutoFacStandardModule());

        using (HttpSelfHostServer serverAE = new HttpSelfHostServer(configAE))
        {
            serverAE.OpenAsync().Wait();
            HttpResponseMessage responseMessage;
            using (var client = new HttpClient())
            {
                responseMessage =
                    client.GetAsync(
                        "http://localhost:53224/AggregationEngine/GetReferenceData/1/Dummy/..."
                        ).Result;
                serverAE.CloseAsync().Wait();
                configAE.Dispose();
                Assert.AreEqual(HttpStatusCode.OK, responseMessage.StatusCode, "Wrong http status returned");

            }
        }

    }

示例控制器

public class GetReferenceDataController : ApiController
{
    private readonly IDeserializeHelper _deserializeHelper;
    private readonly IGetBudgetData _getBudgetData;
    private readonly IRevision _revision;

    public GetReferenceDataController(IDeserializeHelper deserializeHelper, IGetBudgetData getBudgetData, IRevision revision)
    {
        _deserializeHelper = deserializeHelper;
        _getBudgetData = getBudgetData;
        _revision = revision;
    }

    [Authorize]
    [Route("AggregationEngine/GetReferenceData/{budgetId}/{userId}/{filterJSON}")]
    [HttpGet]
    public HttpResponseMessage Get(int budgetId, string userId, [FromUri]string filterJSON)
    {
        FlatBudgetData data = new FlatBudgetData();
        IDataQueryFilter dataQueryFilter = _deserializeHelper.DeserializeToFilterObject(EntityType.UserReferenceLine, _revision.GetLatesRevision(budgetId), userId, filterJSON);
        data.Data = _getBudgetData.GetData(dataQueryFilter);

        string jsonFlatBudget = JsonConvert.SerializeObject(data);

        var jsonResponse = new HttpResponseMessage()
        {
            Content = new StringContent(jsonFlatBudget)
        };
        jsonResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        return jsonResponse;
    }
}

我遵循了以下堆栈线程中的第一个答案并使其正常工作。 Integration Test Web Api With [Authorize]