Search code examples
controllernunithttpcontext

How to user HttpContext AuthenticateAsync method in NUnit test case?


We are using HttpContext Authenticate Async method for External login for Gmail or Microsoft. Login and sign up working fine when using this httpcontext. But when we need to write the NUnit test case for this scenario, I couldn't able to initialize and set claims identity. Write the code for this below scenario

this.externalLoginController.ControllerContext = new ControllerContext();
        this.externalLoginController.ControllerContext.HttpContext = new DefaultHttpContext();
        var testScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
        var principal = new ClaimsPrincipal();
        principal.AddIdentity(new ClaimsIdentity(new[] {
        new Claim(ClaimTypes.Role, "Administrator"),
        new Claim(ClaimTypes.NameIdentifier, "test")
        }, testScheme));

call the function after set httpcontext initialization

 var result = await this.HttpContext.AuthenticateAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme).ConfigureAwait(false);

In this case facing the issue like "value cannot be null: Parameter(provider)".

I need to use Authenticate async method from HttpContext for NUnit test case.

Please advise.

Thanks, Saravanan.


Solution

  • I have used the below code to mock the AuthenticateAsync method and return the AuthenticateResult.

        public class TestAuthenticationHandler : AuthenticationHandler<TestAuthenticationOptions>
    {
        protected override Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            var authenticationTicket = new AuthenticationTicket(
                                             new ClaimsPrincipal(Options.Identity),
                                             new AuthenticationProperties(),
                                             this.Options.AuthenticationScheme);
    
            return Task.FromResult(AuthenticateResult.Success(authenticationTicket));
        }
    }
    

    So that I am able to use this method in Unit test and passes the case.