Unit test AuthorizationHandler

我的梦境 提交于 2019-12-21 03:55:28

问题


I used the resource based authorization pattern in .NET Core 2.1 as described here. The only problem that I have is I have no idea on how to test my AuthorizationHandler cleanly.

Anyone here did something like that already?

AuthorizationHandler sample (from the above link):

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 { }

回答1:


All the required dependencies are available for an isolated unit test.

the desired method under test HandleRequirementAsync is accessible via the Task HandleAsync(AuthorizationHandlerContext context)

/// <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);
        }
    }
}

And that member is only dependent on AuthorizationHandlerContext which has a constructor as follows

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

    //... omitted for brevity
}

Source

Simple isolated unit test that verifies the expected behavior of 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
}


来源:https://stackoverflow.com/questions/51272610/unit-test-authorizationhandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!