我正在尝试集成测试我的 Web API Controller 。该应用程序使用 JWT 针对资源服务器对用户进行身份验证。
为了假脱机应用程序,我使用 Microsoft.OWIN.Testing 中的 TestServer。
我可以像浏览器一样通过执行登录来获取有效的 JWT。然后,我继续将 JWT 添加到请求中,如下所示:
request.AddHeader("Authorization", "Bearer " + accessToken.RawData);
该 header 也会到达 OWIN 管道。但是,所有受 [Authorize]
属性保护的 Controller 在调用时都会返回 401 Unauthorized
。
该 API 使用 Thinktecture 的 IdentityServer3 进行保护,相关部分如下所示:
var authority = "http://localhost:8080/idsrv/";
var parameters = new TokenValidationParameters() { ValidAudiences = new[] { "implicitclient" } };
var options = new IdentityServerBearerTokenAuthenticationOptions
{
Authority = authority,
TokenValidationParameters = parameters
};
app.UseIdentityServerBearerTokenAuthentication(options);
var configuration = new WebApiConfiguration(this.container);
configuration.Configuration(app);
我真的不知道在哪里寻找问题的线索,因此非常感谢您的帮助。
最佳答案
您想真正使用 token 中间件进行测试吗?我的意思是 - 您不是在测试 token 中间件本身 - 而是基于某些身份验证结果的 Controller 逻辑。
只需编写一个小型内联中间件,将 Context.Authentication.User
设置为您想要测试的某些 ClaimsPrincipal。
app.Use(async (ctx, next) => { ctx.Authentication.User = somePrincipal; wait next() };
关于c# - 对使用 IdentityServer3 进行承载身份验证的 ASP.NET WebAPI Controller 进行集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38095255/