18

I am using ASP.NET core to build an API, and I am trying to upgrade from .NET core 2.2 to .NET core 3.1.

I am using the [Authorize] attribute to secure the API endpoints and I want to bypass it during integration tests.

I have managed to to create a custom AuthenticationHandler that authenticates a fake user, and an authorization handler that authorizes anybody (including anonymous users).

My problem is that the user injected in the Authentication handler is not propagated to the Authorization handler and the filter DenyAnonymousAuthorizationRequirement fails because the User in the context is null.

Has anyone dealt with something similar?

By the way, the class DenyAnonymousAuthorizationRequirement is a Microsoft class, I copied the code as it appeared in the IDE just for the post here.

My custom AuthenticationHandler:

  public class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
  {
        public TestAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
                               ILoggerFactory logger,
                               UrlEncoder encoder,
                               ISystemClock clock)
            : base(options, logger, encoder, clock) { }

        protected override Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            ClaimsPrincipal fakeUser = FakeUserUtil.FakeUser();
            var ticket = new AuthenticationTicket(fakeUser, "Test");
            var result = AuthenticateResult.Success(ticket);
            return Task.FromResult(result);
        }
  }

The AuthorizationRequirement:

public class DenyAnonymousAuthorizationRequirement : AuthorizationHandler<DenyAnonymousAuthorizationRequirement>, IAuthorizationRequirement
    {

        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, DenyAnonymousAuthorizationRequirement requirement)
        {
            var user = context.User;
            var userIsAnonymous =
                user?.Identity == null ||
                !user.Identities.Any(i => i.IsAuthenticated);
            if (!userIsAnonymous)
            {
                context.Succeed(requirement);
            }
            return Task.CompletedTask;
        }
    }

The code in the ConfigureServices method that uses the above classes:

 public void ConfigureServices(IServiceCollection services)
 {

            services.AddAuthentication("Test")
                    .AddScheme<AuthenticationSchemeOptions, TestAuthHandler>("Test", null);
            services.AddAuthorization(configure =>
            {
                var builder = new AuthorizationPolicyBuilder(new List<string> {"Test"}.ToArray())
                    .AddRequirements(new DenyAnonymousAuthorizationRequirement());
                configure.DefaultPolicy = builder.Build();
            });
            services.AddControllers()
                    .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
                    .AddNewtonsoftJson(options =>
                                           options.SerializerSettings.ReferenceLoopHandling =
                                               ReferenceLoopHandling.Ignore);

}
1

2 Answers 2

21

Have a related problem and have stumbled on this article here

it shows that you can override the user that is set in the HttpContext this way:

class FakeUserFilter : IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        context.HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity(new List<Claim>
        {
            new Claim(ClaimTypes.NameIdentifier, "123"),
            new Claim(ClaimTypes.Name, "Test user"),
            new Claim(ClaimTypes.Email, "[email protected]"),
            new Claim(ClaimTypes.Role, "Admin")
        }));

        await next();
    }
}

and then inject it in ConfigureTestServices:

builder.ConfigureTestServices(services =>
        {
            services.AddMvc(options =>
            {                   
                options.Filters.Add(new AllowAnonymousFilter());
                options.Filters.Add(new FakeUserFilter());
            })
            .AddApplicationPart(typeof(Startup).Assembly);
        });

Hope this helps

Sign up to request clarification or add additional context in comments.

2 Comments

After looking for more than an hour, your solution saved me :) thanks.
the blog post is great, much better than the docs. another post from gunnar helped me getting different users for integration testing: gunnarpeipman.com/aspnet-core-integration-tests-users-roles
3

Check out this documentation https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1 at "Mock Authentication" session. I think that you need to add this code after create you client:

client.DefaultRequestHeaders.Authorization = 
    new AuthenticationHeaderValue("Test");

2 Comments

I checked the documentation. It covers Authentication but not Authorization. My AuthHandler is basically the one for the doc pages.
I had the same problema and I have fixed using this package github.com/DOMZE/fake-authentication-jwtbearer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.