public void GivenGoogleReturnedAnError_AuthenticateClient_ThrowsAnException()
            {
                // Arrange.
                var googleProvider = new GoogleProvider("aa", "bb");
                const string existingState = "Oops! - Tasselhoff Burrfoot";
                var queryStringParameters = new NameValueCollection
                {
                    {
                        "error",
                        "I dont' always use bayonets. But when I do, I transport them on Aircraft Carriers."
                    },
                    {"state", existingState}
                };
                var googleAuthenticationServiceSettings = new GoogleAuthenticationServiceSettings
                                                          {
                                                              State = existingState,
                                                              CallBackUri = new Uri("http://2p1s.com")
                                                          };
                // Act.
                var result = Assert.Throws<AuthenticationException>(
                    () => googleProvider.AuthenticateClient(googleAuthenticationServiceSettings, queryStringParameters));

                // Assert.
                Assert.NotNull(result);
                Assert.Equal(
                    "Failed to retrieve an authorization code from Google. The error provided is: I dont' always use bayonets. But when I do, I transport them on Aircraft Carriers.",
                    result.Message);
            }
            public void GivenADifferentStateValue_AuthenticateClient_ThrowsAnException()
            {
                // Arrange.
                var googleProvider = new GoogleProvider("aa", "bb");
                var queryStringParameters = new NameValueCollection
                {
                    {"code", "a"},
                    {"state", "b"}
                };
                var googleAuthenticationServiceSettings = new GoogleAuthenticationServiceSettings
                                                          {
                                                              State = "asdasd",
                                                              CallBackUri = new Uri("http://2p1s.com")
                                                          };
                

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

                // 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);
            }
        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 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 GivenSomeState_RedirectToAuthenticate_ReturnsAUri()
            {
                // Arrange.
                var googleProvider = new GoogleProvider("aa", "bb", new Uri("http://wwww.google.com"));

                // Act.
                var result = googleProvider.RedirectToAuthenticate("bleh");

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("https://accounts.google.com/o/oauth2/auth?client_id=aa&redirect_uri=http://wwww.google.com/&response_type=code&state=bleh&scope=https://www.googleapis.com/auth/userinfo.profile%20https://www.googleapis.com/auth/userinfo.email", result.AbsoluteUri);
            }
コード例 #6
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 GivenNoCodeAndNoErrorWasReturned_AuthenticateClient_ThrowsAnException()
            {
                // Arrange.
                var googleProvider = new GoogleProvider("aa", "bb");
                const string existingState = "http://2p1s.com";
                var queryStringParameters = new NameValueCollection
                {
                    {"aaa", "bbb"},
                    {"state", existingState}
                };

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

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("No code parameter provided in the response query string from Google.", result.Message);
            }
            public void GivenADifferentStateValue_AuthenticateClient_ThrowsAnException()
            {
                // Arrange.
                var googleProvider = new GoogleProvider("aa", "bb");
                var queryStringParameters = new NameValueCollection
                {
                    {"code", "a"},
                    {"state", "b"}
                };

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

                // 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);
            }
コード例 #11
0
        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);
        }
        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 GivenNoCodeAndNoErrorWasReturned_AuthenticateClient_ThrowsAnException()
            {
                // Arrange.
                var googleProvider = new GoogleProvider("aa", "bb");
                const string existingState = "Oops! - Tasselhoff Burrfoot";
                var queryStringParameters = new NameValueCollection
                {
                    {"aaa", "bbb"},
                    {"state", existingState}
                };
                var googleAuthenticationServiceSettings = new GoogleAuthenticationServiceSettings
                                                          {
                                                              State = existingState,
                                                              CallBackUri = new Uri("http://2p1s.com")
                                                          };

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

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("No code parameter provided in the response query string from Google.", result.Message);
            }
            public void GivenAnErrorOccuredWhileTryingToRetrieveAnAccessToken_AuthenticateClient_ThrowsAnException()
            {
                // Arrange.
                var mockRestClient = new Mock<IRestClient>();
                const string errorMessage =
                    "If God says he was not created by a creator, does that mean: god is an aetheist?";
                mockRestClient.Setup(x => x.Execute<AccessTokenResult>(It.IsAny<IRestRequest>()))
                              .Throws(new InvalidOperationException(errorMessage));
                var googleProvider = new GoogleProvider("aa", "bb", null,
                                                        new RestClientFactory(mockRestClient.Object));
                const string existingState = "http://2p1s.com";
                var queryStringParameters = new NameValueCollection
                {
                    {"code", "aaa"},
                    {"state", existingState}
                };

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

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("Failed to obtain an Access Token from Google.", result.Message);
                Assert.NotNull(result.InnerException);
                Assert.Equal(errorMessage, result.InnerException.Message);
            }
            public void GivenANullCallbackUriWhileTryingToRetrieveAnAccessToken_AuthenticateClient_ThrowsAnException()
            {
                // Arrange.
                var mockRestClient = new Mock<IRestClient>();
                var mockRestResponse = new Mock<IRestResponse<AccessTokenResult>>();
                mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.BadRequest);
                mockRestResponse.Setup(x => x.StatusDescription).Returns("Bad Request");
                mockRestResponse.Setup(x => x.Content).Returns("{\n  \"error\" : \"invalid_request\"\n}");
                mockRestClient
                    .Setup(x => x.Execute<AccessTokenResult>(It.IsAny<IRestRequest>()))
                    .Returns(mockRestResponse.Object);
                var googleProvider = new GoogleProvider("aa", "bb", null,
                                                        new RestClientFactory(mockRestClient.Object));
                const string existingState = "http://2p1s.com";
                var queryStringParameters = new NameValueCollection
                {
                    {"code", "aaa"},
                    {"state", existingState}
                };

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

                // Assert.
                Assert.NotNull(result);
                Assert.Equal(
                    "Failed to obtain an Access Token from Google OR the the response was not an HTTP Status 200 OK. Response Status: BadRequest. Response Description: Bad Request",
                    result.Message);
            }
            public void GivenExecutingRetrieveSomeUserInfo_AuthenticateClient_ReturnsAnAuthenticatedClient()
            {
                // Arrange.
                const string accessToken = "aaa";
                const int expiresIn = 100;
                var mockRestResponse = new Mock<IRestResponse<AccessTokenResult>>();
                mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK);
                mockRestResponse.Setup(x => x.Data).Returns(new AccessTokenResult
                {
                    AccessToken = accessToken,
                    ExpiresIn = expiresIn,
                    IdToken =
                        "What if that sexy girl in that pop up chat really does want to meet people in my area?",
                    TokenType = "overly attached girlfriend"
                });

                var userInfoResult = new UserInfoResult
                {
                    Email = "aaa",
                    FamilyName = "bbb",
                    Gender = "male",
                    GivenName = "ccc",
                    Id = "ddd",
                    Link = "http://2p1s.com",
                    Locale = "en-au",
                    Name = "eee",
                    Picture = "http://2p1s.com/zomg",
                    VerifiedEmail = true
                };
                var mockRestResponseUserInfo = new Mock<IRestResponse<UserInfoResult>>();
                mockRestResponseUserInfo.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK);
                mockRestResponseUserInfo.Setup(x => x.Data).Returns(userInfoResult);

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

                mockRestClient.
                    Setup(x => x.Execute<UserInfoResult>(It.IsAny<IRestRequest>()))
                              .Returns(mockRestResponseUserInfo.Object);

                var googleProvider = new GoogleProvider("aa", "bb", null,
                                                        new RestClientFactory(mockRestClient.Object));
                const string existingState = "http://2p1s.com";

                var queryStringParameters = new NameValueCollection
                {
                    {"code", accessToken},
                    {"state", existingState}
                };

                // Act.
                var result = googleProvider.AuthenticateClient(queryStringParameters, existingState);

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("google", result.ProviderName);
                Assert.Equal(accessToken, result.AccessToken);
                Assert.True(DateTime.UtcNow < result.AccessTokenExpiresOn);
                Assert.NotNull(result.UserInformation);
                Assert.Equal(GenderType.Male, result.UserInformation.Gender);
                Assert.Equal(userInfoResult.Id, result.UserInformation.Id);
                Assert.Equal(userInfoResult.Locale, result.UserInformation.Locale);
                Assert.Equal(userInfoResult.Name, result.UserInformation.Name);
                Assert.Equal(userInfoResult.Picture, result.UserInformation.Picture);
                Assert.Equal(userInfoResult.GivenName, result.UserInformation.UserName);
            }
            public void GivenExecutingUserInfoWorksButIsMissingSomeRequiredData_AuthenticateClient_ThrowsAnException()
            {
                // Arrange.
                var mockRestResponse = new Mock<IRestResponse<AccessTokenResult>>();
                mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK);
                mockRestResponse.Setup(x => x.Data).Returns(new AccessTokenResult
                {
                    AccessToken = "aaa",
                    ExpiresIn = 100,
                    IdToken =
                        "What if that sexy girl in that pop up chat really does want to meet people in my area?",
                    TokenType = "overly attached girlfriend"
                });

                var mockRestResponseUserInfo = new Mock<IRestResponse<UserInfoResult>>();
                mockRestResponseUserInfo.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK);
                mockRestResponseUserInfo.Setup(x => x.Data).Returns(new UserInfoResult()); // Missing required info.

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

                mockRestClient.
                    Setup(x => x.Execute<UserInfoResult>(It.IsAny<IRestRequest>()))
                              .Returns(mockRestResponseUserInfo.Object);

                var googleProvider = new GoogleProvider("aa", "bb", null,
                                                        new RestClientFactory(mockRestClient.Object));
                const string existingState = "http://2p1s.com";
                var queryStringParameters = new NameValueCollection
                {
                    {"code", "aaa"},
                    {"state", existingState}
                };

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

                // Assert.
                Assert.NotNull(result);
                Assert.Equal(
                    "We were unable to retrieve the User Id from Google API, the user may have denied the authorization.",
                    result.Message);
            }
            public void GivenExecutingUserInfoThrowsAnException_AuthenticateClient_ThrowsAnException()
            {
                // Arrange.
                var mockRestResponse = new Mock<IRestResponse<AccessTokenResult>>();
                mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK);
                mockRestResponse.Setup(x => x.Data).Returns(new AccessTokenResult
                {
                    AccessToken = "aaa",
                    ExpiresIn = 100,
                    IdToken =
                        "What if that sexy girl in that pop up chat really does want to meet people in my area?",
                    TokenType = "overly attached girlfriend"
                });

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

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

                mockRestClient.
                    Setup(x => x.Execute<UserInfoResult>(It.IsAny<IRestRequest>()))
                              .Returns(mockRestResponseUserInfo.Object);

                var googleProvider = new GoogleProvider("aa", "bb", null,
                                                        new RestClientFactory(mockRestClient.Object));
                const string existingState = "http://2p1s.com";
                var queryStringParameters = new NameValueCollection
                {
                    {"code", "aaa"},
                    {"state", existingState}
                };

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

                // Assert.
                Assert.NotNull(result);
                Assert.Equal(
                    "Failed to obtain User Info from Google OR the the response was not an HTTP Status 200 OK. Response Status: Unauthorized. Response Description: Unauthorized",
                    result.Message);
            }
            public void GivenAnRequestTokenWithMissingParameters_AuthenticateClient_ThrowsAnException()
            {
                // Arrange.
                var mockRestClient = new Mock<IRestClient>();
                var mockRestResponse = new Mock<IRestResponse<AccessTokenResult>>();
                mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK);
                mockRestResponse.Setup(x => x.Data).Returns(new AccessTokenResult());
                mockRestClient
                    .Setup(x => x.Execute<AccessTokenResult>(It.IsAny<IRestRequest>()))
                    .Returns(mockRestResponse.Object);
                var googleProvider = new GoogleProvider("aa", "bb", null,
                                                        new RestClientFactory(mockRestClient.Object));
                const string existingState = "http://2p1s.com";
                var queryStringParameters = new NameValueCollection
                {
                    {"code", "aaa"},
                    {"state", existingState}
                };

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

                // Assert.
                Assert.NotNull(result);
                Assert.Equal(
                    "Retrieved a Google Access Token but it doesn't contain one or more of either: access_token, expires_in or token_type",
                    result.Message);
            }
            public void GivenAnInvalidRequestToken_AuthenticateClient_ThrowsAnException()
            {
                // Arrange.
                var mockRestResponse = new Mock<IRestResponse<AccessTokenResult>>();
                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<AccessTokenResult>(It.IsAny<IRestRequest>()))
                    .Returns(mockRestResponse.Object);
                var googleProvider = new GoogleProvider("aa", "bb", null,
                                                        new RestClientFactory(mockRestClient.Object));
                const string existingState = "Oops! - Tasselhoff Burrfoot";
                var queryStringParameters = new NameValueCollection
                {
                    {"code", "aaa"},
                    {"state", existingState}
                };
                var googleAuthenticationServiceSettings = new GoogleAuthenticationServiceSettings
                                                          {
                                                              State = existingState,
                                                              CallBackUri = new Uri("http://2p1s.com")
                                                          };

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

                // Assert.
                Assert.NotNull(result);
                Assert.Equal(
                    "Failed to obtain an Access Token from Google OR the the response was not an HTTP Status 200 OK. Response Status: Unauthorized. Response Description: Unauthorized",
                    result.Message);
            }