c# – 单元测试AuthorizationHandler

我在.NET Core 2.1中使用了基于资源的授权模式,如here所述.我唯一的问题是我不知道如何干净地测试我的AuthorizationHandler.

这里有人做过类似的事吗?

AuthorizationHandler示例(来自上面的链接):

public class DocumentAuthorizationHandler : 
    AuthorizationHandler<SameAuthorRequirement, Document>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                   SameAuthorRequirement requirement,
                                                   Document resource)
    {
        if (context.User.Identity?.Name == resource.Author)
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}

public class SameAuthorRequirement : IAuthorizationRequirement { }

解决方法:

所有必需的依赖项都可用于隔离单元测试.

可以通过Task HandleAsync(AuthorizationHandlerContext context)访问测试中的所需方法HandleRequirementAsync

/// <summary>
/// Makes a decision if authorization is allowed.
/// </summary>
/// <param name="context">The authorization context.</param>
public virtual async Task HandleAsync(AuthorizationHandlerContext context)
{
    if (context.Resource is TResource)
    {
        foreach (var req in context.Requirements.OfType<TRequirement>())
        {
            await HandleRequirementAsync(context, req, (TResource)context.Resource);
        }
    }
}

该成员仅依赖于AuthorizationHandlerContext,它具有如下构造函数

public AuthorizationHandlerContext(
    IEnumerable<IAuthorizationRequirement> requirements,
    ClaimsPrincipal user,
    object resource) {

    //... omitted for brevity
}

Source

简单的隔离单元测试,用于验证DocumentAuthorizationHandler的预期行为.

public async Task DocumentAuthorizationHandler_Should_Succeed() {
    //Arrange    
    var requirements = new [] { new SameAuthorRequirement()};
    var author = "author";
    var user = new ClaimsPrincipal(
                new ClaimsIdentity(
                    new Claim[] {
                        new Claim(ClaimsIdentity.DefaultNameClaimType, author),
                    },
                    "Basic")
                );
    var resource = new Document {
        Author = author
    };
    var context = new AuthorizationHandlerContext(requirements, user, resource);
    var subject = new DocumentAuthorizationHandler();

    //Act
    await subject.HandleAsync(context);

    //Assert
    context.HasSucceeded.Should().BeTrue(); //FluentAssertions
}
上一篇:限制文件下载php


下一篇:五、WebApi建立authorization server