I've got a policy that I want to test in C#
public class WorkflowCreatePolicy
{
public AuthorizationPolicy AuthorizationPolicy =>
new AuthorizationPolicyBuilder()
.RequireClaim("scope", "WorkflowAdmin")
.Build();
}
Does anyone know of a way to test the AuthorizationPolicy to confirm that the scope "WorkflowAdmin" is successful and all others aren't?
This is what I see when I inspect the object:
I've managed to find this website: Authorization Handler Unit Tests but its talking about testing handlers and has code that marks the auth attempt as successful.
i'm not sure if this is getting close or not. It currently doesn't pass
[Test]
public void GivenPolicyName_WhenICallPolicyChecks_ThenItPasses()
{
ClaimsPrincipal user = new ClaimsPrincipal(new ClaimsIdentity(new List<Claim> { new Claim(CustomClaims.Scope, "WorkflowAdmin") }));
WorkflowCreatePolicy workflowCreatePolicy = new WorkflowCreatePolicy();
AuthorizationHandlerContext authorizationHandlerContext = new AuthorizationHandlerContext(workflowCreatePolicy.AuthorizationPolicy.Requirements, user, null);
Assert.That(authorizationHandlerContext.HasSucceeded, Is.EqualTo(true));
}
See this test in the ASP.NET Core Security Unit Tests. I've taken the pattern from it and applied it your policy.
Found it :)
Under the hood an
AuthorizationPolicy
is just a collection of authorization handlers. Methods likeRequireClaim
add handlers build by Microsoft to the collection. In this case theClaimsAuthorizationRequirement
which inherits fromAuthorizationHandler
.To validate if a user passes an
AuthorizationPolicy
you need anAuthorizationService
which will call all policies. TheDefaultAuthorizationService
will stop after the first handler has failed to authenticate the user. If you do not register anotherAuthorizationService
this one will be used.So you could build the
AuthorizationService
by yourself and call theAuthorizeAsync
method on it. Just be aware that you need to register your customAuthorizationHandler
's too if you want to test against them.You can use this method like the following.
IMHO that's something you would want to test with integration tests.
Unit testing it is covered by the ASP.NET Core and at the end of the day you want to make sure that access to your end-points are protected as you expect.
That you can do with TestServer.
It's the composition of the app that shall be tested at that point: Making sure that calling your end-points without the desired claim will result in a 403.