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

问题描述 投票:1回答:1

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

我有的问题是手动生成一个虚假的accessstoken,用于填充AuthenticationHeaderValueHttpClient请求。搜索了一个有效的工作解决方案,但我没有成功。

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

asp.net-core integration-testing xunit openid-connect aspnet-contrib
1个回答
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);
}
© www.soinside.com 2019 - 2024. All rights reserved.