Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test AuthorizationHandler

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 how to test my AuthorizationHandler cleanly.

Anyone here done 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 { }
like image 514
Patrice Cote Avatar asked Jul 10 '18 19:07

Patrice Cote


1 Answers

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
}
like image 62
Nkosi Avatar answered Oct 10 '22 05:10

Nkosi