是否可以编写一个可以测试 AuthorizationPolicy 对象的测试? [英] Is it possible to write a test that can test an AuthorizationPolicy Object?

查看:30
本文介绍了是否可以编写一个可以测试 AuthorizationPolicy 对象的测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个策略要在 C# 中测试

I've got a policy that I want to test in C#

public class WorkflowCreatePolicy
{
    public AuthorizationPolicy AuthorizationPolicy =>
        new AuthorizationPolicyBuilder()
            .RequireClaim("scope", "WorkflowAdmin")
            .Build();
}

有谁知道测试 AuthorizationPolicy 以确认范围WorkflowAdmin"成功而所有其他人不成功的方法?

Does anyone know of a way to test the AuthorizationPolicy to confirm that the scope "WorkflowAdmin" is successful and all others aren't?

这是我检查对象时看到的:

This is what I see when I inspect the object:

我设法找到了这个网站:Authorization Handler Unit Tests 但它谈论的是测试处理程序,并且具有将 auth 尝试标记为成功的代码.

I've managed to find this website: Authorization Handler Unit Tests but its talking about testing handlers and has code that marks the auth attempt as successful.

我不确定这是否接近.目前没有通过

i'm not sure if this is getting close or not. It currently doesn't pass

[Test]
public void GivenPolicyName_WhenICallPolicyChecks_ThenItPasses()
{
    ClaimsPrincipal user = new ClaimsPrincipal(new ClaimsIdentity(new List<Claim> { new Claim(CustomClaims.Scope, "WorkflowAdmin") }));

    WorkflowCreatePolicy workflowCreatePolicy = new WorkflowCreatePolicy();

    AuthorizationHandlerContext authorizationHandlerContext = new AuthorizationHandlerContext(workflowCreatePolicy.AuthorizationPolicy.Requirements, user, null);

    Assert.That(authorizationHandlerContext.HasSucceeded, Is.EqualTo(true));
}

推荐答案

参见 此测试 在 ASP.NET Core 安全单元测试中.我已经从中借鉴了模式并将其应用于您的政策.

See this test in the ASP.NET Core Security Unit Tests. I've taken the pattern from it and applied it to your policy.

[Fact]
public async Task ShouldAllowIfScopeClaimWorkflowAdminIsPresent()
{
    // Arrange
    var authorizationService = BuildAuthorizationService(services =>
    {
        services.AddAuthorization(options =>
        {
            options.AddPolicy("SomePolicyName", new WorkflowCreatePolicy()
               .AuthorizationPolicy);
        });
    });
    var user = new ClaimsPrincipal(new ClaimsIdentity(
        new Claim[] { new Claim("scope", "WorkflowAdmin") }));

    // Act
    var allowed = await authorizationService.AuthorizeAsync(user, "SomePolicyName");

    // Assert
    Assert.True(allowed.Succeeded);
}

private IAuthorizationService BuildAuthorizationService(
    Action<IServiceCollection> setupServices = null)
{
    var services = new ServiceCollection();
    services.AddAuthorization();
    services.AddLogging();
    services.AddOptions();
    setupServices?.Invoke(services);
    return services.BuildServiceProvider().GetRequiredService<IAuthorizationService>();
}

这篇关于是否可以编写一个可以测试 AuthorizationPolicy 对象的测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆