繁体   English   中英

集成测试使用IdentityServer3的承载身份验证的ASP.NET WebAPI控制器

[英]Integration testing ASP.NET WebAPI controllers that use bearer authentication with identityserver3

我正在尝试集成测试我的Web api控制器。 该应用程序使用JWT来针对资源服务器对用户进行身份验证。

为了后台处理该应用程序,我使用了Microsoft.OWIN.Testing中找到的TestServer。

我可以通过执行登录来获得有效的JWT,就像浏览器一样。 然后,我将JWT添加到请求中,如下所示:

request.AddHeader("Authorization", "Bearer " + accessToken.RawData);

该标头也到达OWIN管道中。 但是,被[Authorize] -attribute保护的所有控制器在被调用时都返回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);

我真的不知道在哪里可以找到该问题的任何指针,因此可以提供任何帮助。

您是否真的要使用令牌中间件进行测试? 我的意思是-您不是在测试令牌中间件本身-而是基于某些身份验证结果的控制器逻辑。

只需编写一个小型内联中间件,即可将Context.Authentication.User设置为您要测试的某些ClaimsPrincipal。

app.Use(async (ctx, next) => { ctx.Authentication.User = somePrincipal; await next() };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM