对使用IdentityServer3的承载身份验证的ASP.NET WebAPI控制器进行集成测试 [英] Integration testing ASP.NET WebAPI controllers that use bearer authentication with identityserver3

查看:430
本文介绍了对使用IdentityServer3的承载身份验证的ASP.NET WebAPI控制器进行集成测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to integration test my web api controllers. The application uses JWTs to authenticate users against the resource server.

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

To spool up the application, I'm using the TestServer found in Microsoft.OWIN.Testing.

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

I can obtain a valid JWT by performing a login as a browser would do. I then proceed to add the JWT to the request as follows:

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

该标头也到达OWIN管道中.但是,所有受[Authorize]属性保护的控制器在调用时都返回401 Unauthorized.

That header also arrives in the OWIN pipeline. However, all controllers protected with the [Authorize]-attribute return 401 Unauthorized when invoked.

Thinktecture使用IdentityServer3保护该API,相关部分如下所示:

The API is protected using IdentityServer3 by Thinktecture, the relevant section looks like this:

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.

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

Just write a small inline middleware that sets Context.Authentication.User to some ClaimsPrincipal you want to test with.

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

这篇关于对使用IdentityServer3的承载身份验证的ASP.NET WebAPI控制器进行集成测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆