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 GivenNoValidAccessTokenParams_AuthenticateClient_ThrowsAnAuthenticationException()
            {
                // Arrange.
                var mockRestClient = new Mock<IRestClient>();
                mockRestClient.Setup(x => x.Execute(It.IsAny<IRestRequest>())).Returns(It.IsAny<IRestResponse>);
                var facebookProvider = new FacebookProvider("a", "b",
                                                            null, new RestClientFactory(mockRestClient.Object));
                const string existingState = "Oops! - Tasselhoff Burrfoot";
                var queryStringParameters = new NameValueCollection
                {
                    {"state", existingState} // No code param.
                };
                var facebookAuthenticationSettings = new FacebookAuthenticationServiceSettings
                                                     {
                                                         State = existingState
                                                     };

                // Act.
                var result =
                    Assert.Throws<AuthenticationException>(
                        () => facebookProvider.AuthenticateClient(facebookAuthenticationSettings, queryStringParameters));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("No code parameter provided in the response query string from Facebook.", result.Message);
            }
                GivenSomeErrorOccuredWhileTryingToRetrieveAccessToken_AuthenticateClient_ThrowsAnAuthenticationException
                ()
            {
                // Arrange.
                var mockRestClient = new Mock<IRestClient>();
                mockRestClient.Setup(x => x.Execute(It.IsAny<IRestRequest>())).Returns(It.IsAny<IRestResponse>);
                var facebookProvider = new FacebookProvider("a", "b",
                                                            null, new RestClientFactory(mockRestClient.Object));
                const string existingState = "Oops! - Tasselhoff Burrfoot";
                var queryStringParameters = new NameValueCollection
                {
                    {"state", existingState},
                    {"error_reason", "aaa"},
                    {"error", "bbb"},
                    {"error_description", "ccc"}
                };
                var facebookAuthenticationSettings = new FacebookAuthenticationServiceSettings
                                                     {
                                                         State = existingState
                                                     };
                // Act.
                var result =
                    Assert.Throws<AuthenticationException>(
                        () => facebookProvider.AuthenticateClient(facebookAuthenticationSettings, queryStringParameters));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("Reason: aaa. Error: bbb. Description: ccc.", result.Message);
            }
        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);
            }
        }
            public void GivenAFacebookCallback_CheckCallback_RetrievesAnAccessTokenAnUserData()
            {
                // Arrange.
                const string state = "blah";
                var mockWebClientWrapper = MoqUtilities.MockedIWebClientWrapper();
                var facebookProvider = new FacebookProvider("a", "b", new Uri("http://www.google.com"),
                                                            mockWebClientWrapper.Object);
                var authenticationService = new AuthenticationService(facebookProvider);
                var mockRequestBase = new Mock<HttpRequestBase>();
                mockRequestBase.Setup(x => x.Params).Returns(new NameValueCollection
                                                                 {
                                                                     {"code", "aaa"},
                                                                     {"state", state}
                                                                 });

                // Act.
                var facebookClient =
                    authenticationService.CheckCallback(mockRequestBase.Object, state) as FacebookClient;

                // Assert.
                Assert.NotNull(facebookClient);
                Assert.NotNull(facebookClient.AccessToken);
                Assert.NotNull(facebookClient.UserInformation);
                Assert.NotNull(facebookClient.UserInformation.Id);
            }
        public HomeController()
        {
            FacebookProvider = new FacebookProvider(FacebookAppId,
                                                    FacebookAppSecret,
                                                    new Uri("http://localhost:1337/home/authenticateCallback"),
                                                    new WebClientWrapper());

            AuthenticationService = new AuthenticationService(FacebookProvider);
        }
            public void GivenDefaultSettingsRequested_RedirectToAuthenticate_ReturnsAUri()
            {
                // Arrange.
                var facebookProvider = new FacebookProvider("aa", "bb", new Uri("http://www.2p1s.com"));
                var facebookAuthenticationServiceSettings = new FacebookAuthenticationServiceSettings();

                // Act.
                var result = facebookProvider.RedirectToAuthenticate(facebookAuthenticationServiceSettings);

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("https://www.facebook.com/dialog/oauth?client_id=aa&scope=email&redirect_uri=http://www.2p1s.com/", result.AbsoluteUri);
            }
            public void GivenAnExistingProvider_AddProvider_ThrowsAnException()
            {
                // Arrange.
                var authenticationService = new AuthenticationService();
                var facebookProvider = new FacebookProvider("a", "b", new Uri("http://www.google.com"));
                // Act.
                authenticationService.AddProvider(facebookProvider);
                var result = Assert.Throws<AuthenticationException>( 
                    () => authenticationService.AddProvider(facebookProvider));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("Trying to add a facebook provider, but one already exists.", result.Message);
            }
Exemplo n.º 9
0
        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);
        }
            public void GivenMobileAndDisplayAreRequested_RedirectToAuthenticate_ReturnsAUri()
            {
                // Arrange.
                var facebookProvider = new FacebookProvider("aa", "bb", new Uri("http://www.2p1s.com"));
                var facebookAuthenticationServiceSettings = new FacebookAuthenticationServiceSettings
                                                            {
                                                                IsMobile = true,
                                                                Display = DisplayType.Touch
                                                            };
                // Act.
                var result = facebookProvider.RedirectToAuthenticate(facebookAuthenticationServiceSettings);

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("https://m.facebook.com/dialog/oauth?client_id=aa&scope=email&display=touch&redirect_uri=http://www.2p1s.com/", result.AbsoluteUri);
            }
            public void GivenSomeInvalidResult_RetrieveAccessToken_ThrowsAnException()
            {
                // Arrange.
                var mockWebClientWrapper = MoqUtilities.MockedIWebClientWrapper(new [] { "asds", null});
                var facebookProvider = new FacebookProvider("a", "b", new Uri("http://www.google.com"),
                                                            mockWebClientWrapper.Object);
                var facebookClient = new FacebookClient
                {
                    Code = "aa",
                    State = "bb"
                };

                // Act.
                var result = Assert.Throws<ArgumentException>(() => facebookProvider.RetrieveAccessToken(facebookClient));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("value should contain 2 elements. value contains currently 1 element.\r\nParameter name: value", result.Message);
            }
            public void GivenAMissingExpiresParam_RetrieveAccessToken_ThrowsAnException()
            {
                // Arrange.
                var mockWebClientWrapper = MoqUtilities.MockedIWebClientWrapper(new[] { "access_token=foo&hi=ohnoes", null });
                var facebookProvider = new FacebookProvider("a", "b", new Uri("http://www.google.com"),
                                                            mockWebClientWrapper.Object);
                var facebookClient = new FacebookClient
                {
                    Code = "aa",
                    State = "bb"
                };

                // Act.
                var result = Assert.Throws<ArgumentException>(() => facebookProvider.RetrieveAccessToken(facebookClient));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("value should be equal to 2. The actual value is 1.\r\nParameter name: value", 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 GivenNoValidAccessTokenParams_AuthenticateClient_ThrowsAnAuthenticationException()
            {
                // Arrange.
                var mockRestClient = new Mock<IRestClient>();
                mockRestClient.Setup(x => x.Execute(It.IsAny<IRestRequest>())).Returns(It.IsAny<IRestResponse>);
                var facebookProvider = new FacebookProvider("a", "b", new Uri("http://www.google.com"),
                                                            mockRestClient.Object);
                const string existingState = "http://2p1s.com";
                var queryStringParameters = new NameValueCollection
                                            {
                                                {"state", existingState} // No code param.
                                            };

                // Act.
                var result = Assert.Throws<AuthenticationException>(() => facebookProvider.AuthenticateClient(queryStringParameters, existingState));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("No code parameter provided in the response query string from Facebook.", result.Message);
            }
            public void GivenAFailedCSRFStateCheck_AuthenticateClient_ThrowsAnAuthenticationException()
            {
                // Arrange.
                var mockRestClient = new Mock<IRestClient>();
                mockRestClient.Setup(x => x.Execute(It.IsAny<IRestRequest>())).Returns(It.IsAny<IRestResponse>);
                var facebookProvider = new FacebookProvider("a", "b", new Uri("http://www.google.com"),
                                                            null, mockRestClient.Object);
                var queryStringParameters = new NameValueCollection
                                            {
                                                {"code", "aaa"},
                                                {"state", "bbb"}
                                            };

                // Act.
                var result = Assert.Throws<AuthenticationException>( () => facebookProvider.AuthenticateClient(queryStringParameters, "meh"));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("The states do not match. It's possible that you may be a victim of a CSRF.", 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 GivenSomeErrorOccuredWhileTryingToRetrieveAccessToken_AuthenticateClient_ThrowsAnAuthenticationException()
            {
                // Arrange.
                var mockRestClient = new Mock<IRestClient>();
                mockRestClient.Setup(x => x.Execute(It.IsAny<IRestRequest>())).Returns(It.IsAny<IRestResponse>);
                var facebookProvider = new FacebookProvider("a", "b", new Uri("http://www.google.com"),
                                                            null, mockRestClient.Object);
                const string existingState = "http://2p1s.com";
                var queryStringParameters = new NameValueCollection
                                            {
                                                {"state", existingState},
                                                {"error_reason", "aaa"},
                                                {"error", "bbb"},
                                                {"error_description", "ccc"}
                                            };

                // Act.
                var result = Assert.Throws<AuthenticationException>(() => facebookProvider.AuthenticateClient(queryStringParameters, existingState));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("Reason: aaa. Error: bbb. Description: ccc.", result.Message);
            }
            public void GivenValidCredentials_RetrieveAccessToken_ReturnsAnAccessTokenAndUserInformation()
            {
                // Arrange.
                var mockWebClientWrapper = MoqUtilities.MockedIWebClientWrapper();
                var facebookProvider = new FacebookProvider("a", "b", new Uri("http://www.google.com"),
                                                            mockWebClientWrapper.Object);
                var facebookClient = new FacebookClient
                                     {
                                         Code = "aa",
                                         State = "bb"
                                     };

                // Act.
                facebookProvider.RetrieveAccessToken(facebookClient);

                // Assert.
                Assert.NotNull(facebookClient);
                Assert.NotNull(facebookClient.AccessToken);
                Assert.NotNull(facebookClient.Code);
                Assert.NotNull(facebookClient.UserInformation);
                Assert.True(facebookClient.UserInformation.Id > 0);
                Assert.NotNull(facebookClient.UserInformation.FirstName);
                Assert.NotNull(facebookClient.UserInformation.LastName);
            }
            public void GivenAnInvalidMeResultThrowsAnException_AuthenticateClient_ThrowsAnAuthenticationException()
            {
                // Arrange.
                var mockRestResponse = new Mock<IRestResponse>();
                mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK);
                mockRestResponse.Setup(x => x.Content).Returns("access_token=foo&expires=1000");

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

                var mockRestClient = new Mock<IRestClient>();
                mockRestClient.Setup(x => x.Execute(It.IsAny<IRestRequest>()))
                    .Returns(mockRestResponse.Object);
                mockRestClient.Setup(x => x.Execute<MeResult>(It.IsAny<IRestRequest>()))
                    .Returns(mockRestResponseApiMe.Object);

                var facebookProvider = new FacebookProvider("a", "b", new Uri("http://www.google.com"),
                                                            null, mockRestClient.Object);
                const string existingState = "http://2p1s.com";
                var queryStringParameters = new NameValueCollection
                                            {
                                                {"state", existingState},
                                                {"code", "whatever"}
                                            };

                // Act.
                var result = Assert.Throws<AuthenticationException>(() => facebookProvider.AuthenticateClient(queryStringParameters, existingState));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("Failed to obtain some Me data from the Facebook api OR the the response was not an HTTP Status 200 OK. Response Status: Unauthorized. Response Description: Unauthorized",
                    result.Message);
            }
            public void GivenSomeInvalidRequestToken_AuthenticateClient_ThrowsAnAuthenticationException()
            {
                // Arrange.
                var mockRestResponse = new Mock<IRestResponse>();
                mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.Unauthorized);
                mockRestResponse.Setup(x => x.StatusDescription).Returns("Unauthorised");
                mockRestResponse.Setup(x => x.Content).Returns("{error:hi there asshat}");

                var mockRestClient = new Mock<IRestClient>();
                mockRestClient.Setup(x => x.Execute(It.IsAny<IRestRequest>()))
                              .Returns(mockRestResponse.Object);

                var facebookProvider = new FacebookProvider("a", "b",
                                                            null, new RestClientFactory(mockRestClient.Object));
                const string existingState = "http://2p1s.com";
                var queryStringParameters = new NameValueCollection
                {
                    {"state", existingState},
                    {"code", "whatever"}
                };

                // Act.
                var result =
                    Assert.Throws<AuthenticationException>(
                        () => facebookProvider.AuthenticateClient(queryStringParameters, existingState));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal(
                    "Failed to obtain an Access Token from Facebook OR the the response was not an HTTP Status 200 OK. Response Status: Unauthorized. Response Description: Unauthorised. Error Content: {error:hi there asshat}",
                    result.Message);
            }
 public AuthenticationService(FacebookProvider facebookProvider)
 {
     // Any one of these can be optional.
     FacebookProvider = facebookProvider;
 }
            public void GivenAnExceptionOccursWhileTryingToRequestAnAccessToken_AuthenticateClient_ThrowsAnAuthenticationException()
            {
                // Arrange.
                const string exceptionMessage = "1st World Problems: Too many rooms in my house. Can't decide where to sleep.";
                var mockRestClient = new Mock<IRestClient>();
                mockRestClient.Setup(x => x.Execute(It.IsAny<IRestRequest>()))
                    .Throws(new Exception(exceptionMessage));
                var facebookProvider = new FacebookProvider("a", "b", new Uri("http://www.google.com"),
                                                            null, mockRestClient.Object);
                const string existingState = "http://2p1s.com";
                var queryStringParameters = new NameValueCollection
                                            {
                                                {"state", existingState},
                                                {"code", "whatever"}
                                            };

                // Act.
                var result = Assert.Throws<AuthenticationException>(() => facebookProvider.AuthenticateClient(queryStringParameters, existingState));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("Failed to retrieve an oauth access token from Facebook.", result.Message);
                Assert.NotNull(result.InnerException);
                Assert.Equal(exceptionMessage, result.InnerException.Message);
            }
            public void GivenSomethingWeirdHappenedWhileTryingToRetrieveMeData_RetrieveAccessToken_ThrowsAnException()
            {
                // Arrange.
                var mockWebClientWrapper = MoqUtilities.MockedIWebClientWrapper(new[] { "access_token=foo&expires=1", "ohcrap" });
                var facebookProvider = new FacebookProvider("a", "b", new Uri("http://www.google.com"),
                                                            mockWebClientWrapper.Object);
                var facebookClient = new FacebookClient
                {
                    Code = "aa",
                    State = "bb"
                };

                // Act.
                var result = Assert.Throws<InvalidOperationException>(() => facebookProvider.RetrieveAccessToken(facebookClient));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("Failed to deserialize the json user information result from Facebook.", result.Message);
            }
            public void GivenAMissingExpiresParam_AuthenticateClient_ThrowsAnAuthenticationException()
            {
                // Arrange.
                var mockRestResponse = new Mock<IRestResponse>();
                mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK);
                mockRestResponse.Setup(x => x.Content).Returns("access_token=foo&omg=pewpew");

                var mockRestClient = new Mock<IRestClient>();
                mockRestClient.Setup(x => x.Execute(It.IsAny<IRestRequest>()))
                    .Returns(mockRestResponse.Object);

                var facebookProvider = new FacebookProvider("a", "b", new Uri("http://www.google.com"),
                                                            null, mockRestClient.Object);
                const string existingState = "http://2p1s.com";
                var queryStringParameters = new NameValueCollection
                                            {
                                                {"state", existingState},
                                                {"code", "whatever"}
                                            };

                // Act.
                var result = Assert.Throws<AuthenticationException>(() => facebookProvider.AuthenticateClient(queryStringParameters, existingState));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("Retrieved a Facebook Access Token but it doesn't contain both the access_token and expires_on parameters.",
                    result.Message);
            }
            public void GivenAValidAccessTokenButApiMeThrowsAnException_AuthenticateClient_ThrowsAnAuthenticationException()
            {
                // Arrange.
                const string exceptionMessage = "1st World Problems: The Pizza guy arrived. Before I finished downloading the movie.";
                var mockRestResponse = new Mock<IRestResponse>();
                mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK);
                mockRestResponse.Setup(x => x.Content).Returns("access_token=foo&expires=1000");

                var mockRestClient = new Mock<IRestClient>();
                mockRestClient.Setup(x => x.Execute(It.IsAny<IRestRequest>()))
                    .Returns(mockRestResponse.Object);
                mockRestClient.Setup(x => x.Execute<MeResult>(It.IsAny<IRestRequest>()))
                    .Throws(new Exception(exceptionMessage));

                var facebookProvider = new FacebookProvider("a", "b", new Uri("http://www.google.com"),
                                                            null, mockRestClient.Object);
                const string existingState = "http://2p1s.com";
                var queryStringParameters = new NameValueCollection
                                            {
                                                {"state", existingState},
                                                {"code", "whatever"}
                                            };

                // Act.
                var result = Assert.Throws<AuthenticationException>(() => facebookProvider.AuthenticateClient(queryStringParameters, existingState));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("Failed to retrieve any Me data from the Facebook Api.", result.Message);
            }
            public void GivenValidCredentials_AuthenticateClient_ReturnsAnAuthenticatedClientWithUserInformation()
            {
                // Arrange.
                var mockRestResponseAccessToken = new Mock<IRestResponse>();
                mockRestResponseAccessToken.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK);
                mockRestResponseAccessToken.Setup(x => x.Content).Returns("access_token=foo&expires=1000");

                var meResult = new MeResult
                               {
                                   Id = 1,
                                   FirstName = "some firstname",
                                   LastName = "some lastname",
                                   Link = "http://whatever",
                                   Locale = "en-au",
                                   Name = "Hi there",
                                   Timezone = 10,
                                   Username = "******",
                                   Verified = true
                               };

                var mockRestResponseApiMe = new Mock<IRestResponse<MeResult>>();
                mockRestResponseApiMe.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK);
                mockRestResponseApiMe.Setup(x => x.Data).Returns(meResult);

                var mockRestClient = new Mock<IRestClient>();
                mockRestClient.Setup(x => x.Execute(It.IsAny<IRestRequest>()))
                    .Returns(mockRestResponseAccessToken.Object);
                mockRestClient.Setup(x => x.Execute<MeResult>(It.IsAny<IRestRequest>()))
                    .Returns(mockRestResponseApiMe.Object);

                var facebookProvider = new FacebookProvider("a", "b", new Uri("http://www.google.com"),
                                                            null, mockRestClient.Object);
                const string existingState = "http://2p1s.com";
                var queryStringParameters = new NameValueCollection
                                            {
                                                {"state", existingState},
                                                {"code", "whatever"}
                                            };
                // Act.
                var result =
                    facebookProvider.AuthenticateClient(queryStringParameters, existingState);

                // Assert.
                Assert.NotNull(result);
                Assert.Equal(ProviderType.Facebook, result.ProviderType);
                Assert.NotNull(result.AccessToken);
                Assert.NotNull(result.UserInformation);
                Assert.False(string.IsNullOrEmpty(result.UserInformation.Id));
                Assert.NotNull(result.UserInformation.Name);
                Assert.NotNull(result.UserInformation.UserName);
            }
            public void GivenAMissingCallBackUriParam_AuthenticateClient_ThrowsAnAuthenticationException()
            {
                // Arrange.
                var mockRestResponse = new Mock<IRestResponse>();
                mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.BadRequest);
                mockRestResponse.Setup(x => x.StatusDescription).Returns("Bad Request");
                mockRestResponse.Setup(x => x.Content)
                                .Returns(
                                    "{\"error\":{\"message\":\"Missing redirect_uri parameter.\",\"type\":\"OAuthException\",\"code\":191}}");

                var mockRestClient = new Mock<IRestClient>();
                mockRestClient.Setup(x => x.Execute(It.IsAny<IRestRequest>()))
                              .Returns(mockRestResponse.Object);

                var facebookProvider = new FacebookProvider("a", "b",
                                                            null, new RestClientFactory(mockRestClient.Object));
                const string existingState = "Oops! - Tasselhoff Burrfoot";
                var queryStringParameters = new NameValueCollection
                {
                    {"state", existingState},
                    {"code", "whatever"}
                };
                var facebookAuthenticationSettings = new FacebookAuthenticationServiceSettings
                                                     {
                                                         State = existingState,
                                                         CallBackUri = new Uri("http://2p1s.com")
                                                     };

                // Act.
                var result =
                    Assert.Throws<AuthenticationException>(
                        () => facebookProvider.AuthenticateClient(facebookAuthenticationSettings, queryStringParameters));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal(
                    "Failed to obtain an Access Token from Facebook OR the the response was not an HTTP Status 200 OK. Response Status: BadRequest. Response Description: Bad Request. Error Content: {\"error\":{\"message\":\"Missing redirect_uri parameter.\",\"type\":\"OAuthException\",\"code\":191}}",
                    result.Message);
            }