public void Initialize(ProviderConfiguration providerConfiguration, IList<string> scope = null, IRestClientFactory restClientFactory = null)
        {
            if (providerConfiguration == null)
            {
                throw new ArgumentNullException("providerConfiguration");
            }

            if (providerConfiguration.Providers == null)
            {
                throw new ArgumentException("providerConfiguration.Providers");
            }

            foreach (ProviderKey provider in providerConfiguration.Providers)
            {
                IAuthenticationProvider authenticationProvider;
                switch (provider.Name.ToLowerInvariant())
                {
                    case "facebook":
                        authenticationProvider = new FacebookProvider(provider, scope, restClientFactory);
                        break;
                    case "google":
                        authenticationProvider = new GoogleProvider(provider, scope, restClientFactory);
                        break;
                    case "twitter":
                        authenticationProvider = new TwitterProvider(provider, restClientFactory);
                        break;
                    default:
                        throw new ApplicationException(
                            "Unhandled ProviderName found - unable to know which Provider Type to create.");
                }

                AddProvider(authenticationProvider);
            }
        }
                GivenExecutingARequestToRetrieveARequestTokenThrowsAnException_AuthenticateClient_ThrowsAnAuthenticationException
                ()
            {
                // Arrange.
                var mockRestClient = new Mock<IRestClient>();
                mockRestClient
                    .Setup(x => x.Execute(It.IsAny<IRestRequest>()))
                    .Throws(new Exception("one does not simply 'get a job'."));
                var twitterProvider = new TwitterProvider("a", "b", new RestClientFactory(mockRestClient.Object));
                var nameValueCollection = new NameValueCollection
                {
                    {"oauth_token", "aaa"},
                    {"oauth_verifier", "bbbb"}
                };
                // Act.
                var result =
                    Assert.Throws<AuthenticationException>(
                        () => twitterProvider.AuthenticateClient(new TwitterAuthenticationServiceSettings(), nameValueCollection));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("Failed to convert Request Token to an Access Token, from Twitter.", result.Message);
                Assert.NotNull(result.InnerException);
                Assert.Equal("one does not simply 'get a job'.", result.InnerException.Message);
            }
        public AuthenticationService(ProviderConfiguration providerConfiguration,
                                     IList<string> scope = null, IRestClient restClient = null)
        {
            Condition.Requires(providerConfiguration).IsNotNull();
            Condition.Requires(providerConfiguration.Providers).IsNotNull();

            var redirectUri = string.Format("{0}?{1}=", providerConfiguration.CallbackUri, providerConfiguration.CallbackQuerystringKey);
            foreach (ProviderKey provider in providerConfiguration.Providers)
            {
                var providerSpecificRedirectUri = new Uri((redirectUri + provider.Name).ToLower());

                IAuthenticationProvider authenticationProvider;
                switch (provider.Name)
                {
                    case ProviderType.Facebook:
                        authenticationProvider = new FacebookProvider(provider, providerSpecificRedirectUri, scope, restClient);
                        break;
                    case ProviderType.Google:
                        authenticationProvider = new GoogleProvider(provider, providerSpecificRedirectUri, scope, restClient);
                        break;
                    case ProviderType.Twitter:
                        authenticationProvider = new TwitterProvider(provider, providerSpecificRedirectUri, restClient);
                        break;
                    default:
                        throw new ApplicationException(
                            "Unhandled ProviderType found - unable to know which Provider Type to create.");
                }

                AddProvider(authenticationProvider);
            }
        }
            public void GivenAValidRequestToken_RedirectToAuthenticate_ReturnsARedirectResult()
            {
                // Arrange.
                var redirectUri =
                    new Uri(
                        "http://api.twitter.com/oauth/authorize?oauth_token=5rlgo7AwGJt67vSoHmF227QMSHXhvmOmhN5YJpRlEo");
                var mockRestResponse = new Mock<IRestResponse>();
                mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK);
                mockRestResponse
                    .Setup(x => x.Content)
                    .Returns("oauth_token=aaaaaaa&oauth_token_secret=asdasd");
                var mockRestClient = new Mock<IRestClient>();
                mockRestClient
                    .Setup(x => x.BuildUri(It.IsAny<IRestRequest>()))
                    .Returns(redirectUri);
                mockRestClient
                    .Setup(x => x.Execute(It.IsAny<IRestRequest>()))
                    .Returns(mockRestResponse.Object);
                var twitterProvider = new TwitterProvider("a", "b", new Uri("http://www.google.com.au"), mockRestClient.Object);

                // Act.
                var result = twitterProvider.RedirectToAuthenticate(new TwitterAuthenticationServiceSettings());

                // Assert.
                Assert.NotNull(result);
                Assert.Equal(result.AbsoluteUri, redirectUri.AbsoluteUri);
            }
        public AccountController(IUserRepository userRepository, IFormsAuthentication formsAuthentication, ITracer tracer, IDietRepository dietRepository)
        {
            _userRepository = userRepository;
            _formsAuthentication = formsAuthentication;
            _tracer = tracer;
            _dietRepository = dietRepository;
            var facebookProvider = new FacebookProvider(FacebookAppId, FacebookAppSecret);
            var twitterProvider = new TwitterProvider(TwitterConsumerKey, TwitterConsumerSecret);
            var googleProvider = new GoogleProvider(GoogleConsumerKey, GoogleConsumerSecret);

            _authenticationService = new AuthenticationService();
            _authenticationService.AddProvider(facebookProvider);
            _authenticationService.AddProvider(twitterProvider);
            _authenticationService.AddProvider(googleProvider);
        }
        private static void RegisterAuthenticationProviders(TinyIoCContainer container)
        {
            Condition.Requires(container).IsNotNull();

            var twitterProvider = new TwitterProvider(TwitterConsumerKey, TwitterConsumerSecret);
            var facebookProvider = new FacebookProvider(FacebookAppId, FacebookAppSecret);
            var googleProvider = new GoogleProvider(GoogleConsumerKey, GoogleConsumerSecret);

            var authenticationService = new AuthenticationService();

            authenticationService.AddProvider(twitterProvider);
            authenticationService.AddProvider(facebookProvider);
            authenticationService.AddProvider(googleProvider);

            container.Register<IAuthenticationService>(authenticationService);
        }
        static HomeController()
        {
            // For the purpose of this example we just made the service static in 
            // a static constructor, normally you would do this using dependency injection
            // but for the take of simplicity we added it it here. Please refer
            // to the Advanced sample for the DI version. Don't use a static constructor
            // like this in your project, please. :)
            var facebookProvider = new FacebookProvider(FacebookAppId, FacebookAppSecret);
            var twitterProvider = new TwitterProvider(TwitterConsumerKey, TwitterConsumerSecret);
            var googleProvider = new GoogleProvider(GoogleConsumerKey, GoogleConsumerSecret);

            AuthenticationService = new AuthenticationService();
            AuthenticationService.AddProvider(facebookProvider);
            AuthenticationService.AddProvider(twitterProvider);
            AuthenticationService.AddProvider(googleProvider);
        }
                GivenAExceptionWhileTryingToRetrieveRequestToken_RedirectToAuthenticate_ThrowsAnAuthenticationException()
            {
                // Arrange.
                var mockRestClient = new Mock<IRestClient>();
                mockRestClient
                    .Setup(x => x.Execute(It.IsAny<IRestRequest>()))
                    .Throws(new Exception("some mock exception"));
                var twitterProvider = new TwitterProvider("a", "b", new Uri("http://www.google.com.au"), mockRestClient.Object);

                // Act.
                var result =
                    Assert.Throws<AuthenticationException>(() => twitterProvider.RedirectToAuthenticate(new TwitterAuthenticationServiceSettings()));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("Failed to obtain a Request Token from Twitter.", result.Message);
                Assert.NotNull(result.InnerException);
                Assert.Equal("some mock exception", result.InnerException.Message);
            }
            public void GivenAUserDeniesAcceptingTheAppAuthorization_AuthenticateClient_ThrowsAnAuthenticationException()
            {
                // Arrange.
                var twitterProvider = new TwitterProvider("a", "b");
                var nameValueCollection = new NameValueCollection
                {
                    {"denied", "JpQ7ZTt1nMeAhIypiOxLrkS3LreHwihKjsJcIJDf4To"}
                };
                // Act.
                var result =
                    Assert.Throws<AuthenticationException>(
                        () => twitterProvider.AuthenticateClient(new TwitterAuthenticationServiceSettings(), nameValueCollection));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal(
                    "Failed to accept the Twitter App Authorization. Therefore, authentication didn't proceed.",
                    result.Message);
            }
        public HomeController()
        {
            var facebookProvider = new FacebookProvider(FacebookAppId, FacebookAppSecret,
                                                        new Uri(
                                                            "http://localhost:1337/home/AuthenticateCallback?providerKey=facebook"));

            var twitterProvider = new TwitterProvider(TwitterConsumerKey, TwitterConsumerSecret,
                                                      new Uri(
                                                          "http://localhost:1337/home/AuthenticateCallback?providerKey=twitter"));

            var googleProvider = new GoogleProvider(GoogleConsumerKey, GoogleConsumerSecret,
                                                    new Uri(
                                                        "http://localhost:1337/home/AuthenticateCallback?providerKey=google"));

            _authenticationService = new AuthenticationService();
            _authenticationService.AddProvider(facebookProvider);
            _authenticationService.AddProvider(twitterProvider);
            _authenticationService.AddProvider(googleProvider);
        }
            public void GivenTheCallbackParamtersAreInvalid_AuthenticateClient_ThrowsAnAuthenticationException()
            {
                // Arrange.
                var mockRestClient = new Mock<IRestClient>();
                mockRestClient
                    .Setup(x => x.Execute(It.IsAny<IRestRequest>()))
                    .Throws<Exception>();
                var twitterProvider = new TwitterProvider("a", "b", new RestClientFactory(mockRestClient.Object));
                var nameValueCollection = new NameValueCollection(); // Missing 2x required params.

                // Act.
                var result =
                    Assert.Throws<ArgumentOutOfRangeException>(
                        () => twitterProvider.AuthenticateClient(new TwitterAuthenticationServiceSettings(), nameValueCollection));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("Specified argument was out of the range of valid values.\r\nParameter name: queryStringParameters",
                    result.Message);
            }
        private static void RegisterAuthenticationProviders(TinyIoCContainer container)
        {
            Condition.Requires(container).IsNotNull();

            var twitterProvider = new TwitterProvider(TwitterConsumerKey, TwitterConsumerSecret,
                                                      new Uri(
                                                          "http://localhost:6969/AuthenticateCallback?providerKey=Twitter"));

            var facebookProvider = new FacebookProvider(FacebookAppId, FacebookAppSecret,
                                                        new Uri(
                                                            "http://localhost:6969/AuthenticateCallback?providerKey=facebook"));

            var googleProvider = new GoogleProvider(GoogleConsumerKey, GoogleConsumerSecret,
                                                    new Uri(
                                                        "http://localhost:6969/AuthenticateCallback?providerKey=google"));

            var authenticationService = new AuthenticationService();
            authenticationService.AddProvider(twitterProvider);
            authenticationService.AddProvider(facebookProvider);
            authenticationService.AddProvider(googleProvider);

            container.Register<IAuthenticationService>(authenticationService);
        }
            public void GivenARequestTokenError_RedirectToAuthenticate_ThrowsAnAuthenticationException()
            {
                // Arrange.
                var mockRestResponse = new Mock<IRestResponse>();
                mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.Unauthorized);
                mockRestResponse.Setup(x => x.StatusDescription).Returns("Unauthorized");
                var mockRestClient = new Mock<IRestClient>();
                mockRestClient
                    .Setup(x => x.Execute(It.IsAny<IRestRequest>()))
                    .Returns(mockRestResponse.Object);
                var twitterProvider = new TwitterProvider("a", "b", new Uri("http://www.google.com.au"), mockRestClient.Object);

                // Act.
                var result =
                    Assert.Throws<AuthenticationException>(() => twitterProvider.RedirectToAuthenticate(new TwitterAuthenticationServiceSettings()));

                // Assert.
                Assert.NotNull(result);
                Assert.Null(result.InnerException);
                Assert.Equal(
                    "Failed to obtain a Request Token from Twitter OR the the response was not an HTTP Status 200 OK. Response Status: Unauthorized. Response Description: Unauthorized",
                    result.Message);
            }
            public void GivenAInvalidRequestToken_RedirectToAuthenticate_ThrowsAnAuthenticationException()
            {
                // Arrange.
                var mockRestResponse = new Mock<IRestResponse>();
                mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK);
                mockRestResponse.Setup(x => x.Content)
                    .Returns("oauth_token=aaaaaaa&missing_an_oauth_token_secret=asdasd");
                var mockRestClient = new Mock<IRestClient>();
                mockRestClient
                    .Setup(x => x.Execute(It.IsAny<IRestRequest>()))
                    .Returns(mockRestResponse.Object);
                var twitterProvider = new TwitterProvider("a", "b", new Uri("http://www.google.com.au"), mockRestClient.Object);

                // Act.
                var result =
                    Assert.Throws<AuthenticationException>(() => twitterProvider.RedirectToAuthenticate(new TwitterAuthenticationServiceSettings()));

                // Assert.
                Assert.NotNull(result);
                Assert.Null(result.InnerException);
                Assert.Equal(
                    "Retrieved a Twitter Request Token but it doesn't contain both the oauth_token and oauth_token_secret parameters.",
                    result.Message);
            }
            public void GivenSomeValidVerifyCredentials_RetrieveUserInformation_ReturnsAnAuthenticatedClient()
            {
                // Arrange.
                var mockRestClient = new Mock<IRestClient>();

                var mockRestResponseRetrieveRequestToken = new Mock<IRestResponse>();
                mockRestResponseRetrieveRequestToken.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK);
                mockRestResponseRetrieveRequestToken.Setup(x => x.Content).Returns("oauth_token=aaa&oauth_token_secret=ccc");

                var verifyCredentialsResult = new VerifyCredentialsResult
                {
                    Name = "Some Name",
                    Id = 1234,
                    Lang = "en-au",
                    ScreenName = "Some-Screen-Name"
                };
                var mockRestResponseVerifyCredentials = new Mock<IRestResponse<VerifyCredentialsResult>>();
                mockRestResponseVerifyCredentials.Setup(x => x.Data).Returns(verifyCredentialsResult);
                mockRestResponseVerifyCredentials.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK);

                mockRestClient
                    .Setup(x => x.Execute(It.IsAny<IRestRequest>()))
                    .Returns(mockRestResponseRetrieveRequestToken.Object);
                mockRestClient
                    .Setup(x => x.Execute<VerifyCredentialsResult>(It.IsAny<IRestRequest>()))
                    .Returns(mockRestResponseVerifyCredentials.Object);

                var twitterProvider = new TwitterProvider("a", "b", new Uri("http://www.google.com.au"), mockRestClient.Object);
                var nameValueCollection = new NameValueCollection
                                          {
                                              {"oauth_token", "aaa"},
                                              {"oauth_verifier", "bbb"}
                                          };

                // Act.
                var result = twitterProvider.AuthenticateClient(nameValueCollection, "asd");

                // Assert.
                Assert.NotNull(result);
                Assert.Equal(ProviderType.Twitter, result.ProviderType);
                Assert.NotNull(result.UserInformation);
                Assert.NotNull(result.UserInformation.Id);
                Assert.NotNull(result.UserInformation.Locale);
                Assert.NotNull(result.UserInformation.Name);
                Assert.NotNull(result.UserInformation.UserName);
            }
            public void GivenAnInvalidVerifyCredentials_RetrieveUserInformation_ThrowsAnAuthenticationException()
            {
                // Arrange.
                var mockRestClient = new Mock<IRestClient>();

                var mockRestResponseRetrieveRequestToken = new Mock<IRestResponse>();
                mockRestResponseRetrieveRequestToken.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK);
                mockRestResponseRetrieveRequestToken.Setup(x => x.Content).Returns("oauth_token=aaa&oauth_token_secret=ccc");

                var mockRestResponseVerifyCredentials = new Mock<IRestResponse<VerifyCredentialsResult>>();
                mockRestResponseVerifyCredentials.Setup(x => x.StatusCode).Returns(HttpStatusCode.Unauthorized);
                mockRestResponseVerifyCredentials.Setup(x => x.StatusDescription).Returns("Unauthorized");

                mockRestClient
                    .Setup(x => x.Execute(It.IsAny<IRestRequest>()))
                    .Returns(mockRestResponseRetrieveRequestToken.Object);
                mockRestClient
                    .Setup(x => x.Execute<VerifyCredentialsResult>(It.IsAny<IRestRequest>()))
                    .Returns(mockRestResponseVerifyCredentials.Object);

                var twitterProvider = new TwitterProvider("a", "b", new Uri("http://www.google.com.au"), mockRestClient.Object);
                var nameValueCollection = new NameValueCollection
                                          {
                                              {"oauth_token", "aaa"},
                                              {"oauth_verifier", "bbb"}
                                          };
                // Act.
                var result = Assert.Throws<AuthenticationException>(() => twitterProvider.AuthenticateClient(nameValueCollection, "asd"));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("Failed to retrieve VerifyCredentials json data OR the the response was not an HTTP Status 200 OK. Response Status: Unauthorized. Response Description: Unauthorized", result.Message);
            }
            public void GivenExecutingVerifyCredentialsThrowsAnException_AuthenticateClient_ThrowsAnAuthenticationException()
            {
                // Arrange.
                const string exceptionMessage = "some mock exception.";
                var mockRestClient = new Mock<IRestClient>();

                var mockRestResponseRetrieveRequestToken = new Mock<IRestResponse>();
                mockRestResponseRetrieveRequestToken.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK);
                mockRestResponseRetrieveRequestToken.Setup(x => x.Content).Returns("oauth_token=aaa&oauth_token_secret=ccc");

                var verifyCredentialsResult = new VerifyCredentialsResult
                                              {
                                                  Name = "Some Name",
                                                  Id = 1234,
                                                  Lang = "en-au",
                                                  ScreenName = "Some-Screen-Name"
                                              };
                var mockRestResponseVerifyCredentials = new Mock<IRestResponse<VerifyCredentialsResult>>();
                mockRestResponseVerifyCredentials.Setup(x => x.Data).Returns(verifyCredentialsResult);

                mockRestClient
                    .Setup(x => x.Execute(It.IsAny<IRestRequest>()))
                    .Returns(mockRestResponseRetrieveRequestToken.Object);
                mockRestClient
                    .Setup(x => x.Execute<VerifyCredentialsResult>(It.IsAny<IRestRequest>()))
                    .Throws(new Exception(exceptionMessage));

                var twitterProvider = new TwitterProvider("a", "b", new Uri("http://www.google.com.au"), mockRestClient.Object);
                var nameValueCollection = new NameValueCollection
                                          {
                                              {"oauth_token", "aaa"},
                                              {"oauth_verifier", "bbb"}
                                          };
                // Act.
                var result = Assert.Throws<AuthenticationException>(() => twitterProvider.AuthenticateClient(nameValueCollection, "asd"));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("Failed to retrieve VerifyCredentials json data from the Twitter Api.", result.Message);
            }
            public void GivenAnRequestTokenWithMissingParameters_AuthenticateClient_ThrowsAnAuthenticationException()
            {
                // Arrange.
                var mockRestClient = new Mock<IRestClient>();
                var mockRestResponse = new Mock<IRestResponse>();
                mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK);
                mockRestClient
                    .Setup(x => x.Execute(It.IsAny<IRestRequest>()))
                    .Returns(mockRestResponse.Object);
                var twitterProvider = new TwitterProvider("a", "b", new Uri("http://www.google.com.au"), mockRestClient.Object);
                var nameValueCollection = new NameValueCollection
                                          {
                                              {"oauth_token", "aaa"}
                                          }; // Missing oauth_secret.
                // Act.
                var result = Assert.Throws<AuthenticationException>(() => twitterProvider.AuthenticateClient(nameValueCollection, "asd"));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("Failed to retrieve an oauth_token and an oauth_token_secret after the client has signed and approved via Twitter.", result.Message);
            }
            public void GivenAnInvalidRequestToken_AuthenticateClient_ThrowsAnAuthenticationException()
            {
                // Arrange.
                var mockRestClient = new Mock<IRestClient>();
                var mockRestResponse = new Mock<IRestResponse>();
                mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.Unauthorized);
                mockRestResponse.Setup(x => x.StatusDescription).Returns("Unauthorized");
                mockRestClient
                    .Setup(x => x.Execute(It.IsAny<IRestRequest>()))
                    .Returns(mockRestResponse.Object);
                var twitterProvider = new TwitterProvider("a", "b", new Uri("http://www.google.com.au"), mockRestClient.Object);
                var nameValueCollection = new NameValueCollection
                                          {
                                              {"oauth_token", "aaa"},
                                              {"oauth_verifier", "bbbb"}
                                          };
                // Act.
                var result = Assert.Throws<AuthenticationException>(() => twitterProvider.AuthenticateClient(nameValueCollection, "asas"));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("Failed to obtain an Access Token from Twitter OR the the response was not an HTTP Status 200 OK. Response Status: Unauthorized. Response Description: Unauthorized", result.Message);
            }
            public void GivenTheCallbackParamtersAreInvalid_AuthenticateClient_ThrowsAnAuthenticationException()
            {
                // Arrange.
                var mockRestClient = new Mock<IRestClient>();
                mockRestClient
                    .Setup(x => x.Execute(It.IsAny<IRestRequest>()))
                    .Throws<Exception>();
                var twitterProvider = new TwitterProvider("a", "b", new Uri("http://www.google.com.au"), mockRestClient.Object);
                var nameValueCollection = new NameValueCollection(); // Missing 2x required params.
                
                // Act.
                var result = Assert.Throws<AuthenticationException>(() => twitterProvider.AuthenticateClient(nameValueCollection, "aa"));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("Failed to retrieve an oauth_token and an oauth_token_secret after the client has signed and approved via Twitter.", result.Message);
            }
            public void GivenAUserDeniesAcceptingTheAppAuthorization_AuthenticateClient_ThrowsAnAuthenticationException()
            {
                // Arrange.
                var mockRestClient = new Mock<IRestClient>();
                var twitterProvider = new TwitterProvider("a", "b", new Uri("http://www.google.com.au"), mockRestClient.Object);
                var nameValueCollection = new NameValueCollection
                                          {
                                              {"denied", "JpQ7ZTt1nMeAhIypiOxLrkS3LreHwihKjsJcIJDf4To"}
                                          };
                // Act.
                var result = Assert.Throws<AuthenticationException>(() => twitterProvider.AuthenticateClient(nameValueCollection, null));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("Failed to accept the Twitter App Authorization. Therefore, authentication didn't proceed.", result.Message);
            }