簡體   English   中英

集成測試使用IdentityServer3的承載身份驗證的ASP.NET WebAPI控制器

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

我正在嘗試集成測試我的Web api控制器。 該應用程序使用JWT來針對資源服務器對用戶進行身份驗證。

為了后台處理該應用程序,我使用了Microsoft.OWIN.Testing中找到的TestServer。

我可以通過執行登錄來獲得有效的JWT,就像瀏覽器一樣。 然后,我將JWT添加到請求中,如下所示:

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

該標頭也到達OWIN管道中。 但是,被[Authorize] -attribute保護的所有控制器在被調用時都返回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);

我真的不知道在哪里可以找到該問題的任何指針,因此可以提供任何幫助。

您是否真的要使用令牌中間件進行測試? 我的意思是-您不是在測試令牌中間件本身-而是基於某些身份驗證結果的控制器邏輯。

只需編寫一個小型內聯中間件,即可將Context.Authentication.User設置為您要測試的某些ClaimsPrincipal。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM