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

喜欢而已 提交于 2019-12-24 01:39:25

问题


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

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

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);

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

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.


回答1:


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.

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



来源:https://stackoverflow.com/questions/38095255/integration-testing-asp-net-webapi-controllers-that-use-bearer-authentication-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!