已经回答了类似的问题here但答案似乎对我不起作用。
我想在使用 JWT 身份验证的 Web Api 中测试身份验证/授权过程。
我的身份验证是通过我添加到我的 HttpConfiguration
中的自定义 MessageHandler
处理的。授权由我想限制访问的 Controller /方法上的简单 [Authorize]
属性处理。
我正在设置我在身份验证期间以这种方式从 token 中提取的主体(在我的自定义 MessageHandler
中):
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null)
{
HttpContext.Current.User = principal;
}
当我在本地 IIS 中手动测试时,整个过程运行良好。
但是当使用像 here 这样的内存托管进行测试时
ApiController.User
属性存储用于通过 [Authorize]
进行授权的 Principal我当前 session 的主体)而不是身份验证期间的一组。
如果我将我的 Thread.CurrentPrincipal
设置为 null,我只会收到错误的请求。
TL;DR 如何使用内存托管测试我的身份验证/授权管道
?因为它在我的测试中将 ApiController.User
值设置为 Thread.CurrentPrincipal
值,而没有获得我在身份验证期间成功设置的值。
我想我可以设法解决实现自定义 [Authorize]
属性获取 Thread.CurrentPrincipal
而不是 ApiController.User
,但我想避免这种情况。
提前致谢。
EDIT 澄清:所有此管道(身份验证然后授权)在正在运行的 IIS 中托管时工作正常(具有在内存托管期间为空的 HttpContext)。我只是想用内存托管来测试它(如果可能的话)。在内存托管测试期间,在我的自定义 MessageHandler
中放置断点,我可以看出 Thread.CurrentPrincipal
设置正确,只是 [Authorize]
似乎并不关心这一点,因为在我的 ApiControllers 中,ApiController.User
属性已经设置为我的 Thread.CurrentPrincipal
值测试(我本地的 Windows session 主体)
最佳答案
我已按照 "Retrieving and Assigning the Current Principal" section of Chapter 15 in "Designing Evolvable Web APIs with ASP.NET" 中列出的指导取得成功:
In ASP.NET Web API version 2.0, you can solve this problem by using the new HttpRequestContext class. First, the current identity should be retrieved and assigned to the current request object, not to a static property. Secondly, different hosts can use different HttpRequestContext implementations
简而言之,在您的消息处理程序中,执行此操作而不是设置当前线程和 HttpContext 的主体:
request.GetRequestContext().Principal = principal;
关于c# - 如何使用自定义身份验证和内存托管进行 ASP.NET Web API 集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22715958/