简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM