Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test code that uses OWIN Cookie Authenthication

I have learned that OWIN has this great Microsoft.Owin.Testing library that lets you test your web application in-memory. However, my site requires authentication before accessing resources which has complicated writing test code.

Is there a convenient way to "mock" authentication when using Microsoft.Owin.Testing?

I would like my unit tests to not need to hit an out-of-process STS and I would prefer not to need to write code that programmatically signs in against an in-memory STS (such as Thinktecture.IdentityServer.v3).

The easiest solution I come up with is to disable the authentication code for the unit tests, of which I am not a fan.

I am using OpenID Connect with Cookie Authentication. Here is a contained example. The configuration strings for the OpenId Connect would need to be filled in for an actual server.

[Test]
public async void AccessAuthenthicatedResourceTest()
{
    const string ClientId = "";
    const string RedirectUri = "";
    const string Authority = "";

    TestServer server = TestServer.Create(
        app =>
            {
                //Configure Open ID Connect With Cookie Authenthication
                app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
                app.UseCookieAuthentication(new CookieAuthenticationOptions());
                app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
                    {
                    ClientId = ClientId,
                    RedirectUri = RedirectUri,
                    Authority = Authority
                    });

                // Requires Authentication
                app.Use(
                    async ( context, next ) =>
                        {
                            var user = context.Authentication.User;
                            if ( user == null
                                 || user.Identity == null
                                 || !user.Identity.IsAuthenticated )
                            {
                                context.Authentication.Challenge();
                                return;
                            }

                            await next();
                        } );

                app.Run( async context => await context.Response.WriteAsync( "My Message" ) );
            } );


    //Do or Bypass authenthication

    HttpResponseMessage message = await server.CreateRequest( "/" ).GetAsync();

    Assert.AreEqual("My Message", await message.Content.ReadAsStringAsync());
}
like image 979
vossad01 Avatar asked Oct 15 '14 13:10

vossad01


1 Answers

I think mocking is to test a part of code in your controller. You can inject fake data for a user using mock. You have to create an Interface for user provider.

 public interface IUserProvider
    {
        string GetUserId();
        string GetUserName();
    }

and inject it to your base class :

 protected BaseController(IUnitOfWork data, IUserProvider userProvider)
        {
            this.data = data;
            this.userProvider = userProvider;
        }

After that you can mock the IUserProvider like so :

 var userMockReposioty = new Mock<IRepository<ApplicationUser>>();
            var userMockUserProvider = new Mock<IUserProvider>();
            userMockUserProvider.Setup(x => x.GetUserName())
                .Returns("FakeUserName");

            userMockUserProvider.Setup(x => x.GetUserId())
              .Returns("c52b2a96-8258-4cb0-b844-a6e443acb04b");

 mockUnitOfWork.Setup(x => x.Users).Returns(userMockReposioty.Object);

I hope that this will help you.

like image 156
Ilia Bakyrdjiev Avatar answered Oct 05 '22 07:10

Ilia Bakyrdjiev