Integration testing ASP.NET WebAPI controllers tha

2019-07-11 18:15发布

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条回答
狗以群分
2楼-- · 2019-07-11 18:33

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

查看更多
登录 后发表回答