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

查看:109
本文介绍了是否可以编写可以测试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以确认范围

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:

我设法找到了该网站:授权处理程序单元测试,但它涉及测试处理程序,并且具有标记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天全站免登陆