private static TestableAuthController GetTestableAuthController(
            IOpenIdRelyingParty relyingParty,
            IFormsAuthentication formsAuth,
            CreateUser createUser,
            GetUserByClaimId getUser,
            string providerUrl = @"http:\\testprovider.com")
        {
            HttpContextBase contextMock    = MvcMockHelpers.FakeHttpContext(providerUrl);
            var             authController = new TestableAuthController(relyingParty, formsAuth, createUser, getUser);

            authController.ControllerContext = new ControllerContext(contextMock, new RouteData(), authController);
            authController.InvokeInitialize(authController.ControllerContext.RequestContext);

            // default routes
            var routes = new RouteCollection();

            routes.MapRoute(
                "Default",                    // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = "" } // Parameter defaults
                );
            authController.Url = new UrlHelper(authController.ControllerContext.RequestContext,
                                               routes);

            return(authController);
        }
        public void WhenProviderRespondsAuthenticated_ThenSetsFormsAuthCookie()
        {
            const string returnUrl        = @"http://returnUrl.com";
            const string claimIdentifier  = @"http://username/";
            var          formsAuthMock    = new Mock <IFormsAuthentication>();
            var          userServicesMock = new Mock <IUserServices>();

            userServicesMock.Setup(ur => ur.GetOrCreateUser(It.IsAny <string>()))
            .Returns(new User())
            .Verifiable();

            formsAuthMock.Setup(f => f.SetAuthCookie(It.IsAny <HttpContextBase>(), It.IsAny <FormsAuthenticationTicket>()))
            .Verifiable();

            TestableAuthController authController = GetTestableAuthController(
                OpenIdRelyingPartyBuilder
                .DefaultParty()
                .ReturnsClaimId(claimIdentifier)
                .Object,
                formsAuthMock.Object,
                userServicesMock.Object, @"http://providerUrl.com");

            ActionResult response = authController.SignInResponse(returnUrl);

            formsAuthMock.Verify();
        }
        public void WhenUserAuthenticatedAndHasNoUserRecord_ThenCreatesOne()
        {
            var createUser = new Mock <CreateUser>(null);
            var getUser    = new Mock <GetUserByClaimId>(null);

            getUser.Setup(r => r.Execute(It.IsAny <string>()))
            .Returns <User>(null)
            .Verifiable();

            createUser.Setup(c => c.Execute(It.IsAny <string>()))
            .Returns(new User {
            })
            .Verifiable();

            TestableAuthController authController = GetTestableAuthController(
                new MockRelyingParty(),
                new Mock <IFormsAuthentication>().Object,
                createUser.Object,
                getUser.Object
                );

            ActionResult result = authController.SignInResponse();

            createUser.VerifyAll();
        }
        public void WhenProviderRespondsAuthenticated_ThenSetsFormsAuthCookie()
        {
            const string claimIdentifier = @"http://username/";
            var          formsAuthMock   = new Mock <IFormsAuthentication>();
            var          createUser      = new Mock <CreateUser>(null);
            var          getUser         = new Mock <GetUserByClaimId>(null);

            getUser.Setup(u => u.Execute(It.IsAny <string>())).Returns(
                new User());

            formsAuthMock.Setup(f => f.SetAuthCookie(It.IsAny <HttpContextBase>(), It.IsAny <FormsAuthenticationTicket>()))
            .Verifiable();

            TestableAuthController authController = GetTestableAuthController(
                OpenIdRelyingPartyBuilder
                .DefaultParty()
                .ReturnsClaimId(claimIdentifier)
                .Object,
                formsAuthMock.Object,
                createUser.Object,
                getUser.Object,
                @"http://providerUrl.com");

            ActionResult response = authController.SignInResponse();

            formsAuthMock.Verify();
        }
        public void WhenProviderRespondsAuthenticatedAndSuppliesMetdata_ThenMetadataSavedToRepository()
        {
            var fetchResponse = new FetchResponse();

            var createUser = new Mock <CreateUser>(null);
            var getUser    = new Mock <GetUserByClaimId>(null);

            getUser.Setup(ur => ur.Execute(It.IsAny <string>()))
            .Returns <User>(null);

            createUser.Setup(c => c.Execute(It.IsAny <string>()))
            .Returns(new User {
            })
            .Verifiable();

            TestableAuthController authController = GetTestableAuthController(
                OpenIdRelyingPartyBuilder.DefaultParty()
                .ReturnFriendlyName("BillyBaroo")
                .ReturnFetchResponse(fetchResponse)
                .Object,
                new Mock <IFormsAuthentication>().Object,
                createUser.Object,
                getUser.Object);

            authController.SignInResponse();

            createUser.VerifyAll();
        }
        public void WhenSigningIn_ThenRedirectsToOpenProvidedAction()
        {
            string providerUrl = @"http://ssomeauthcontroller.com";

            TestableAuthController authController =
                GetTestableAuthController(OpenIdRelyingPartyBuilder.DefaultParty().Object);

            ActionResult response = authController.SignInWithProvider(providerUrl);

            // For the test we ensure that controller responsds with whatever the OpenIdRelyingParty facade returns.
            Assert.IsType(typeof(RedirectResult), response);
        }
        public void WhenProviderRespondsCancelledAuthentication_ThenRedirectsToSignInAction()
        {
            var relyingParty = new MockRelyingParty();

            relyingParty.ResponseMock.SetupGet(r => r.Status).Returns(AuthenticationStatus.Canceled);

            TestableAuthController authController = GetTestableAuthController(relyingParty);

            ActionResult result = authController.SignInResponse();

            Assert.IsType(typeof(RedirectToRouteResult), result);
            Assert.Equal("Index", ((RedirectToRouteResult)result).RouteValues["action"]);
        }
        public void WhenProviderRespondsFailedSignInAuthentication_ThenProvidesErrorMessage()
        {
            var exception    = new ArgumentException("TestException");
            var relyingParty = new MockRelyingParty();

            relyingParty.ResponseMock.SetupGet(r => r.Status).Returns(AuthenticationStatus.Failed);
            relyingParty.ResponseMock.SetupGet(r => r.Exception).Returns(exception);

            TestableAuthController authController = GetTestableAuthController(relyingParty);

            authController.SignInResponse();
            Assert.Equal(exception.Message, authController.TempData["alert"]);
        }
        public void WhenProviderRespondsWithAnythingElse_ThenRedirectsToSignInActionWithMessage()
        {
            var relyingParty = new MockRelyingParty();

            relyingParty.ResponseMock.SetupGet(r => r.Status).Returns(AuthenticationStatus.SetupRequired);

            TestableAuthController authController = GetTestableAuthController(relyingParty);

            ActionResult result = authController.SignInResponse();

            Assert.IsType(typeof(RedirectToRouteResult), result);
            Assert.Equal("Index", ((RedirectToRouteResult)result).RouteValues["action"]);
            Assert.NotNull(authController.TempData["alert"]);
        }
        public void WhenProviderRespondsFailedSignInAuthentication_ThenRedirectsToSignInAction()
        {
            var mockRelyingParty = new MockRelyingParty();

            mockRelyingParty.ResponseMock.SetupGet(r => r.Status).Returns(AuthenticationStatus.Failed);
            mockRelyingParty.ResponseMock.SetupGet(r => r.Exception).Returns(new Exception("Failed"));

            TestableAuthController authController = GetTestableAuthController(mockRelyingParty);

            ActionResult result = authController.SignInResponse(@"http://returnUrl.com");

            Assert.IsType(typeof(RedirectToRouteResult), result);
            Assert.Equal("SignIn", ((RedirectToRouteResult)result).RouteValues["action"]);
        }
        public void WhenSigningInWithoutSpecifyingProviderUrl_ThenRedirectsToOpenProvidedAction()
        {
            var relyingPartyMock = new Mock <IOpenIdRelyingParty>();

            relyingPartyMock
            .Setup(x => x.RedirectToProvider(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <FetchRequest>()))
            .Throws(new Exception("Relying party expects a url, a null or empty string will raise an exception."));

            TestableAuthController authController = GetTestableAuthController(relyingPartyMock.Object);

            var result = authController.SignInWithProvider(null) as RedirectToRouteResult;

            Assert.NotNull(result);
            Assert.Equal("Index", result.RouteValues["action"]);
        }
        public void WhenProviderCreateRequestThrows_ThenRedirectsToSignInActionWithAMessage()
        {
            var relyingParty = new Mock <IOpenIdRelyingParty>();

            relyingParty.Setup(
                r => r.RedirectToProvider(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <FetchRequest>()))
            .Throws(new Exception("Some Provider Exception"));

            TestableAuthController authController = GetTestableAuthController(relyingParty.Object);

            ActionResult result = authController.SignInWithProvider(@"http://providerUrl");

            Assert.IsType(typeof(RedirectToRouteResult), result);
            Assert.Equal("SignIn", ((RedirectToRouteResult)result).RouteValues["action"]);
            Assert.NotNull(authController.TempData["Message"]);
        }
        public void WhenUserAuthenticatedAndHasNoUserRecord_ThenCreatesOne()
        {
            var userServicesMock = new Mock <IUserServices>();

            userServicesMock.Setup(ur => ur.GetOrCreateUser(It.IsAny <string>()))
            .Returns(new User())
            .Verifiable();

            TestableAuthController authController = GetTestableAuthController(
                new MockRelyingParty(),
                new Mock <IFormsAuthentication>().Object,
                userServicesMock.Object
                );

            ActionResult result = authController.SignInResponse(@"http://returnUrl.com");

            userServicesMock.Verify();
        }
        public void WhenSigningIn_ThenSetsReturnUrlToCorrectSchema()
        {
            string providerUrl = @"http://ssomeauthcontroller.com";

            var relyingPartyMock = new Mock <IOpenIdRelyingParty>();

            TestableAuthController authController = GetTestableAuthController(relyingPartyMock.Object);

            Mock <HttpRequestBase> requestMock = Mock.Get(authController.Request);

            requestMock.SetupGet(r => r.Url)
            .Returns(new Uri(@"https://nothingmattersbutschema.com", UriKind.Absolute));

            ActionResult response = authController.SignInWithProvider(providerUrl);

            relyingPartyMock.Verify(x => x.RedirectToProvider(
                                        It.IsAny <string>(),
                                        It.Is <string>(s => s.StartsWith("https:")),
                                        It.IsAny <FetchRequest>()), "Incorrect schema applied for return URL.");
        }
        public void WhenProviderRespondsAuthenticated_ThenSerializesNewUserIdInUserData()
        {
            const string claimIdentifier     = @"http://username/";
            FormsAuthenticationTicket ticket = null;

            var formsAuthMock = new Mock <IFormsAuthentication>();

            formsAuthMock.Setup(f => f.SetAuthCookie(It.IsAny <HttpContextBase>(), It.IsAny <FormsAuthenticationTicket>()))
            .Callback <HttpContextBase, FormsAuthenticationTicket>((h, t) => ticket = t);

            var createUser = new Mock <CreateUser>(null);
            var getUser    = new Mock <GetUserByClaimId>(null);

            getUser.Setup(x => x.Execute(It.Is <string>(u => u == claimIdentifier)))
            .Returns(new User
            {
                AuthorizationId = claimIdentifier,
                DisplayName     = "TestDisplayName",
                UserId          = 55,
            });

            TestableAuthController authController = GetTestableAuthController(
                OpenIdRelyingPartyBuilder
                .DefaultParty()
                .ReturnsClaimId(claimIdentifier)
                .Object,
                formsAuthMock.Object,
                createUser.Object,
                getUser.Object,
                @"http://providerUrl.com");

            ActionResult response = authController.SignInResponse();

            // Assert
            UserInfo userInfo = UserInfo.FromString(ticket.UserData);

            Assert.NotNull(userInfo);
            Assert.Equal(55, userInfo.UserId);
        }
        public void WhenProviderRespondsAuthenticatedAndSuppliesMetdata_ThenMetadataSavedToRepository()
        {
            const string returnUrl     = @"http://doesnotmatter.com";
            var          fetchResponse = new FetchResponse();

            var userServicesMock = new Mock <IUserServices>();

            userServicesMock.Setup(ur => ur.GetOrCreateUser(It.IsAny <string>()))
            .Returns(new User())
            .Verifiable();

            TestableAuthController authController = GetTestableAuthController(
                OpenIdRelyingPartyBuilder.DefaultParty()
                .ReturnFriendlyName("BillyBaroo")
                .ReturnFetchResponse(fetchResponse)
                .Object,
                new Mock <IFormsAuthentication>().Object,
                userServicesMock.Object);

            authController.SignInResponse(returnUrl);

            userServicesMock.Verify();
        }
        public void WhenUserAuthenticatedAndRegistered_ThenRedirectsToHomeIndex()
        {
            var createUser = new Mock <CreateUser>(null);
            var getUser    = new Mock <GetUserByClaimId>(null);

            getUser.Setup(u => u.Execute(It.IsAny <string>())).Returns(
                new User());

            TestableAuthController authController = GetTestableAuthController(
                OpenIdRelyingPartyBuilder.DefaultParty().Object,
                new Mock <IFormsAuthentication>().Object,
                createUser.Object,
                getUser.Object
                );

            ActionResult response = authController.SignInResponse();

            Assert.IsType(typeof(RedirectToRouteResult), response);
            var route = ((RedirectToRouteResult)response).RouteValues;

            Assert.Equal("Dashboard", route["controller"]);
            Assert.Equal("Index", route["action"]);
        }
        public void WhenUserAuthenticatedAndRegistered_ThenRedirectsToHomeIndex()
        {
            const string returnUrl        = @"http://returnUrl.com";
            var          userServicesMock = new Mock <IUserServices>();

            userServicesMock.Setup(u => u.GetUserByClaimedIdentifier(It.IsAny <string>())).Returns(
                new User());

            userServicesMock.Setup(ur => ur.GetOrCreateUser(It.IsAny <string>()))
            .Returns(new User())
            .Verifiable();

            TestableAuthController authController = GetTestableAuthController(
                OpenIdRelyingPartyBuilder.DefaultParty().Object,
                new Mock <IFormsAuthentication>().Object,
                userServicesMock.Object
                );

            ActionResult response = authController.SignInResponse(returnUrl);

            Assert.IsType(typeof(RedirectToRouteResult), response);
            Assert.Equal("Dashboard", ((RedirectToRouteResult)response).RouteName);
        }
        private static TestableAuthController GetTestableAuthController(IOpenIdRelyingParty relyingParty,
                                                                        IFormsAuthentication formsAuth,
                                                                        IUserServices userServices,
                                                                        string providerUrl = @"http:\\testprovider.com")
        {
            HttpContextBase contextMock = MvcMockHelpers.FakeHttpContext(providerUrl);
            var authController = new TestableAuthController(relyingParty, formsAuth, userServices);
            authController.ControllerContext = new ControllerContext(contextMock, new RouteData(), authController);
            authController.InvokeInitialize(authController.ControllerContext.RequestContext);

            // default routes
            var routes = new RouteCollection();
            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new {controller = "Home", action = "Index", id = ""} // Parameter defaults
                );
            authController.Url = new UrlHelper(authController.ControllerContext.RequestContext,
                                               routes);

            return authController;
        }