DEV Community

Dennis
Dennis

Posted on

Integration testing in Umbraco 10+: Extending the backoffice

This post builds upon what we did in my previous post where I introduced integration testing in Umbraco.
If you've followed along and set up your own integration testing project, you may have been tempted to try it out on a backoffice controller. You'll be disappointed to find out that your requests are rejected by authentication. In this post I'll be explaining how to fix that:

Authentication in Umbraco

Umbraco authorizes requests to the backoffice with the framework that asp.net provides. You can get more in-depth understanding of how that works in the microsoft documentation about authentication and authorization. All you need to know for integration testing is that authorization works with policies, which are collections of requirements, and that we can modify these collections.

To make our integration tests work in the backoffice, we will redefine the requirements for the backoffice so that we will always have access.

Making the modifications

The first thing that we need is a new requirement:

internal class TestRequirement
    : IAuthorizationRequirement
{ }
Enter fullscreen mode Exit fullscreen mode

The next thing we need is a handler that can tell the framework that this new requirement is met:

internal class TestAuthorizationHandler : AuthorizationHandler<TestRequirement>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TestRequirement requirement)
    {
        context.Succeed(requirement);
        return Task.CompletedTask;
    }
}
Enter fullscreen mode Exit fullscreen mode

Finally, we need to change MyCustomWebApplicationFactory and replace the original authorization requirements with our new one:

protected override void ConfigureWebHost(IWebHostBuilder builder)
{
    // ... Everything that was here before (see previous blog post)

    builder.ConfigureServices(ConfigureServices);
}

private void ConfigureServices(IServiceCollection obj)
{
    // Register our newly created handler so it can be picked up by the authorization framework
    obj.AddSingleton<IAuthorizationHandler, TestAuthorizationHandler>();

    obj.AddAuthorization(options =>
    {
        options.AddPolicy(AuthorizationPolicies.BackOfficeAccess, policy =>
        {
            // Take Umbraco's backoffice policy, remove all requirements and add our new requirement here.
            policy.Requirements.Clear();
            policy.AddRequirements(new TestRequirement());
        });
    });
}
Enter fullscreen mode Exit fullscreen mode

And that is all!

Conclusion

Once again, Umbraco makes our life surprisingly easy. I wasn't expecting this little effort to make integration tests in Umbraco backoffice controllers work.

Leave a comment if you have any questions, remarks or feedback, I would love to hear your opinion!

Latest comments (0)