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 { }
All the required dependencies are available for an isolated unit test.
the desired method under test
HandleRequirementAsync
is accessible via theTask HandleAsync(AuthorizationHandlerContext context)
And that member is only dependent on
AuthorizationHandlerContext
which has a constructor as followsSource
Simple isolated unit test that verifies the expected behavior of
DocumentAuthorizationHandler
.