c# - 对使用 IdentityServer3 进行承载身份验证的 ASP.NET WebAPI Controller 进行集成测试

标签 c# asp.net-web-api owin identityserver3

我正在尝试集成测试我的 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/

相关文章:

c# - Json.Net - 序列化 "compressing"?

c# - Web API 中的单元测试自定义路由

asp.net - 将 ASP.NET MVC5 身份验证添加到现有项目

c# - 非泛型类型 'ActionResult' 不能与类型参数一起使用

javascript - 将字符串数组绑定(bind)到导航栏

asp.net-web-api - 什么是 AuthorizeEndpointPath?

asp.net-web-api - SignalR 响应覆盖 header

c# - 如何在应用程序运行时更改 GridView.ItemTemplate?

c# - .net 中 C++ 的包装类?

c# - Linq 隐式类型范围变量