我刚刚使用ASP.net身份OWIN和OAuth 2为我的Web API添加了基于令牌的安全性。因此,我在所有测试中都获得了405个未经授权的错误。我如何模拟securitycontext。我已经看到一些样本,其他的已经覆盖了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;
}
}