使用OpenIdConnect服务器(ASOS)进行手动访问生成

时间:2016-12-16 19:37:33

标签: asp.net-core integration-testing xunit openid-connect aspnet-contrib

我正在 asp.net核心1.1 项目中实施Aspnet OpenIdConnect Server (ASOS),目前正在尝试使用Microsoft实施一些集成测试(xunit& moq) .AspNetCore.TestHost.TestServer。

我遇到的问题是手动生成虚假的accessstoken,用于为AuthenticationHeaderValue请求填充HttpClient。为此搜索了一个有效的解决方案,但是我没有成功。

所以我的问题:任何人都有一个提示,如何手动为TestServer生成accessstokens而无需调用ASOS的令牌端点进行测试?

1 个答案:

答案 0 :(得分:1)

虽然ASOS故意阻止您从任意位置创建令牌(它们只能在OpenID Connect请求期间生成),但您可以直接使用底层ASP.NET Core API生成将被OAuth2验证中间件接受的假令牌:

var provider = container.GetRequiredService<IDataProtectionProvider>();
var protector = provider.CreateProtector(
    nameof(OpenIdConnectServerMiddleware),
    OpenIdConnectServerDefaults.AuthenticationScheme, "Access_Token", "v1");

var format = new TicketDataFormat(protector);

var identity = new ClaimsIdentity();
identity.AddClaim(new Claim(ClaimTypes.Name, "Bob le Bricoleur"));

var ticket = new AuthenticationTicket(
    new ClaimsPrincipal(identity),
    new AuthenticationProperties(),
    OpenIdConnectServerDefaults.AuthenticationScheme);

var token = format.Protect(ticket);

也就是说,如果您想测试自己的令牌保护API,它很少是最有效的方法。相反,我建议设置HttpContext.User或使用OAuth2验证中间件事件来使用虚假身份而不涉及加密操作。

您还可以模拟AccessTokenFormat

[Fact]
public async Task ValidTokenAllowsSuccessfulAuthentication()
{
    // Arrange
    var server = CreateResourceServer();

    var client = server.CreateClient();

    var request = new HttpRequestMessage(HttpMethod.Get, "/");
    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "valid-token");

    // Act
    var response = await client.SendAsync(request);

    // Assert
    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    Assert.Equal("Fabrikam", await response.Content.ReadAsStringAsync());
}


private static TestServer CreateResourceServer(Action<OAuthValidationOptions> configuration = null)
{
    var builder = new WebHostBuilder();

    var format = new Mock<ISecureDataFormat<AuthenticationTicket>>(MockBehavior.Strict);

    format.Setup(mock => mock.Unprotect(It.Is<string>(token => token == "invalid-token")))
          .Returns(value: null);

    format.Setup(mock => mock.Unprotect(It.Is<string>(token => token == "valid-token")))
          .Returns(delegate
          {
              var identity = new ClaimsIdentity(OAuthValidationDefaults.AuthenticationScheme);
              identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "Fabrikam"));

              var properties = new AuthenticationProperties();

              return new AuthenticationTicket(new ClaimsPrincipal(identity),
                  properties, OAuthValidationDefaults.AuthenticationScheme);
          });

    builder.ConfigureServices(services =>
    {
        services.AddAuthentication();
    });

    builder.Configure(app =>
    {
        app.UseOAuthValidation(options =>
        {
            options.AccessTokenFormat = format.Object;

            // Run the configuration delegate
            // registered by the unit tests.
            configuration?.Invoke(options);
        });

        // Add the middleware you want to test here.

        app.Run(context =>
        {
            if (!context.User.Identities.Any(identity => identity.IsAuthenticated))
            {
                return context.Authentication.ChallengeAsync();
            }

            var identifier = context.User.FindFirst(ClaimTypes.NameIdentifier).Value;
            return context.Response.WriteAsync(identifier);
        });
    });

    return new TestServer(builder);
}