简体   繁体   English

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

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

I'm trying to integration test my web api controllers. 我正在尝试集成测试我的Web api控制器。 The application uses JWTs to authenticate users against the resource server. 该应用程序使用JWT来针对资源服务器对用户进行身份验证。

To spool up the application, I'm using the TestServer found in Microsoft.OWIN.Testing. 为了后台处理该应用程序,我使用了Microsoft.OWIN.Testing中找到的TestServer。

I can obtain a valid JWT by performing a login as a browser would do. 我可以通过执行登录来获得有效的JWT,就像浏览器一样。 I then proceed to add the JWT to the request as follows: 然后,我将JWT添加到请求中,如下所示:

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

That header also arrives in the OWIN pipeline. 该标头也到达OWIN管道中。 However, all controllers protected with the [Authorize] -attribute return 401 Unauthorized when invoked. 但是,被[Authorize] -attribute保护的所有控制器在被调用时都返回401 Unauthorized

The API is protected using IdentityServer3 by Thinktecture, the relevant section looks like this: 该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);

I don't really know where to look for any pointers to the problem, so any help is appreciated. 我真的不知道在哪里可以找到该问题的任何指针,因此可以提供任何帮助。

Do you want to really test with the token middleware? 您是否真的要使用令牌中间件进行测试? I mean - you are not testing the token middleware itself - but the controller logic based on certain authentication outcomes. 我的意思是-您不是在测试令牌中间件本身-而是基于某些身份验证结果的控制器逻辑。

Just write a small inline middleware that sets Context.Authentication.User to some ClaimsPrincipal you want to test with. 只需编写一个小型内联中间件,即可将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