带有多种身份验证方案的.NET Core API测试

时间:2020-01-02 11:03:52

标签: c# asp.net-core identityserver4

我正在开发一个应用程序,它支持两种不同的身份验证方案。

  • 基于cookie的方案,用于使用用户名/密码凭据登录。通过身份验证后,SPA将重定向到我的身份验证服务器,并且用户将在此执行身份验证。 (因此,没有ResourceOwner / Password Grant流)。
  • 基于Jwt的方案用于外部IdP身份验证,我支持Facebook身份验证(对于移动应用程序)和警卫队/ api / api2。

服务器是整体服务器,其中IdP和资源服务器作为一个服务器收集。我正在使用IdentityServer4作为身份验证框架。

我的代码受IS4演示项目的启发: https://github.com/IdentityServer/IdentityServer4.Demo/blob/master/src/IdentityServer4Demo/Quickstart/Account/ExternalController.cs

我将以下两个客户端都配置为使用代码流作为Grant类型:

            new Client
            {
                ClientId = "mobileclient",
                ClientName = "Client 1",
                ClientSecrets = {new Secret("secret".Sha256())},
                AllowedGrantTypes = GrantTypes.Code,
                AllowedScopes = {"openid", "profile", "email"},
                RequireConsent = false,
                RequirePkce = true,
                AccessTokenLifetime = 3600,
                RequireClientSecret = false,
                AllowAccessTokensViaBrowser = true,
                AllowOfflineAccess = true,
                AccessTokenType = AccessTokenType.Jwt,
                RefreshTokenUsage = TokenUsage.ReUse,
                RedirectUris = {"http://localhost:54362/"},
                PostLogoutRedirectUris = {"https://notused"},
            },
            new Client
            {
                ClientId = "adminclient",
                ClientName = "Client 2",
                ClientSecrets = {new Secret("secret".Sha256())},
                RequireConsent = false,
                AllowedGrantTypes = GrantTypes.Code,
                RequirePkce = true,
                RequireClientSecret = false,
                AllowedScopes = {"openid", "profile", "email"},
                AllowOfflineAccess = true,
                RefreshTokenUsage = TokenUsage.ReUse,
                RedirectUris = {"http://localhost:4200/auth-callback"},
                PostLogoutRedirectUris = {"http://localhost:5000/Account/Login"},
            },

我想创建我的API的集成测试,但是我正在努力找到一种很好的方法/原则集,说明如何使用两种身份验证方案对我的API的请求进行测试。

我正在使用WebApplicationFactory类,并且根据Microsoft的文档, https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1#mock-authentication,他们建议我应该使用一些随机值来模拟身份验证处理程序,但是那样我就不会测试我的原始身份验证逻辑,这就是API测试的目的。

所以我想听听,如果有人对以下内容有好的建议:

  • 如何使用外部IdP(Facebook)基于身份验证的JWT来测试API 1(客户端1)?
  • 如何设置用于测试API 2(客户端2)的身份验证cookie?

谢谢。

0 个答案:

没有答案