【问题标题】:Testing Web API controllers protected with [Authorize]测试受 [Authorize] 保护的 Web API 控制器
【发布时间】:2015-03-15 20:55:48
【问题描述】:

我刚刚使用 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;
    }
}

【问题讨论】:

    标签: asp.net .net asp.net-web-api oauth-2.0 integration-testing


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2011-09-09
      • 2020-09-23
      • 1970-01-01
      • 1970-01-01
      • 2016-03-28
      • 1970-01-01
      • 1970-01-01
      • 2019-06-22
      • 1970-01-01
      相关资源
      最近更新 更多