Exemple #1
0
        private string RetrieveAccessToken(string code, Uri redirectUri)
        {
            if (string.IsNullOrEmpty(code))
            {
                throw new ArgumentNullException("code");
            }

            if (redirectUri == null ||
                string.IsNullOrEmpty(redirectUri.AbsoluteUri))
            {
                throw new ArgumentNullException("redirectUri");
            }

            IRestResponse response;

            try
            {
                var restRequest = new RestRequest("oauth/access_token");
                restRequest.AddParameter("client_id", _clientId);
                restRequest.AddParameter("client_secret", _clientSecret);
                restRequest.AddParameter("code", code);
                restRequest.AddParameter("redirect_uri", redirectUri.AbsoluteUri);

                var restClient = RestClientFactory.CreateRestClient(BaseUrl);
                response = restClient.Execute(restRequest);
            }
            catch (Exception exception)
            {
                throw new AuthenticationException("Failed to retrieve an oauth access token from Facebook.", exception);
            }

            if (response == null ||
                response.StatusCode != HttpStatusCode.OK)
            {
                // {"error":{"message":"Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request","type":"OAuthException","code":100}}

                throw new AuthenticationException(
                          string.Format(
                              "Failed to obtain an Access Token from Facebook OR the the response was not an HTTP Status 200 OK. Response Status: {0}. Response Description: {1}. Error Content: {2}",
                              response == null ? "-- null response --" : response.StatusCode.ToString(),
                              response == null ? string.Empty : response.StatusDescription,
                              response == null ? string.Empty : response.Content));
            }

            var querystringParameters = HttpUtility.ParseQueryString(response.Content);
            var accessToken           = querystringParameters["access_token"];
            int expires;
            var expiresOn = int.TryParse(querystringParameters["expires"], out expires)
                                ? DateTime.UtcNow.AddSeconds(expires)
                                : DateTime.MinValue;

            if (string.IsNullOrEmpty(accessToken) ||
                expiresOn <= DateTime.UtcNow)
            {
                throw new AuthenticationException(
                          "Retrieved a Facebook Access Token but it doesn't contain both the access_token and expires_on parameters.");
            }

            return(accessToken);
        }
Exemple #2
0
        protected override IRestResponse <AccessTokenResult> ExecuteRetrieveAccessToken(string authorizationCode,
                                                                                        Uri redirectUri)
        {
            if (string.IsNullOrEmpty(authorizationCode))
            {
                throw new ArgumentNullException("authorizationCode");
            }

            if (redirectUri == null ||
                string.IsNullOrEmpty(redirectUri.AbsoluteUri))
            {
                throw new ArgumentNullException("redirectUri");
            }

            var restRequest = new RestRequest("v2.4/oauth/access_token");

            restRequest.AddParameter("client_id", PublicApiKey);
            restRequest.AddParameter("client_secret", SecretApiKey);
            restRequest.AddParameter("code", authorizationCode);
            restRequest.AddParameter("redirect_uri", redirectUri.AbsoluteUri.ToLowerInvariant());
            restRequest.AddHeader("Content-Type", "application/json");
            restRequest.AddParameter("format", "json");

            var restClient = RestClientFactory.CreateRestClient(BaseUrl);

            TraceSource.TraceVerbose("Retrieving Access Token endpoint: {0}",
                                     restClient.BuildUri(restRequest).AbsoluteUri);

            return(restClient.Execute <AccessTokenResult>(restRequest));
        }
Exemple #3
0
        protected override IRestResponse <AccessTokenResult> ExecuteRetrieveAccessToken(string authorizationCode,
                                                                                        Uri redirectUri)
        {
            if (string.IsNullOrEmpty(authorizationCode))
            {
                throw new ArgumentNullException("authorizationCode");
            }

            if (redirectUri == null ||
                string.IsNullOrEmpty(redirectUri.AbsoluteUri))
            {
                throw new ArgumentNullException("redirectUri");
            }

            // Reference: https://launchpad.37signals.com/authorization/token?type=web_server&client_id=your-client-id&redirect_uri=your-redirect-uri&client_secret=your-client-secret&code=verification-code

            var restRequest = new RestRequest("/authorization/token", Method.POST);

            restRequest.AddParameter("type", "web_server");
            restRequest.AddParameter("client_id", PublicApiKey);
            restRequest.AddParameter("client_secret", SecretApiKey);
            restRequest.AddParameter("redirect_uri", redirectUri.AbsoluteUri);
            restRequest.AddParameter("code", authorizationCode);

            var restClient = RestClientFactory.CreateRestClient(BaseUri);

            TraceSource.TraceVerbose("Retrieving Access Token endpoint: {0}; Post Params: {1}",
                                     restClient.BuildUri(restRequest).AbsoluteUri,
                                     string.Join(", ", restRequest.Parameters));

            return(restClient.Execute <AccessTokenResult>(restRequest));
        }
        protected override IRestResponse <AccessTokenResult> ExecuteRetrieveAccessToken(string authorizationCode,
                                                                                        Uri redirectUri)
        {
            if (string.IsNullOrEmpty(authorizationCode))
            {
                throw new ArgumentNullException("authorizationCode");
            }

            if (redirectUri == null ||
                string.IsNullOrEmpty(redirectUri.AbsoluteUri))
            {
                throw new ArgumentNullException("redirectUri");
            }

            var restRequest = new RestRequest("/oauth20_token.srf");

            restRequest.AddParameter("client_id", PublicApiKey);
            restRequest.AddParameter("redirect_uri", redirectUri);
            restRequest.AddParameter("client_secret", SecretApiKey);
            restRequest.AddParameter("code", authorizationCode);
            restRequest.AddParameter("grant_type", "authorization_code");

            var restClient = RestClientFactory.CreateRestClient("https://login.live.com/oauth20_token.srf");

            TraceSource.TraceVerbose("Retrieving Access Token endpoint: {0}",
                                     restClient.BuildUri(restRequest).AbsoluteUri);

            return(restClient.Execute <AccessTokenResult>(restRequest));
        }
        protected override IRestResponse <AccessTokenResult> ExecuteRetrieveAccessToken(string authorizationCode,
                                                                                        Uri redirectUri)
        {
            if (string.IsNullOrEmpty(authorizationCode))
            {
                throw new ArgumentNullException("authorizationCode");
            }

            if (redirectUri == null ||
                string.IsNullOrEmpty(redirectUri.AbsoluteUri))
            {
                throw new ArgumentNullException("redirectUri");
            }

            var restRequest = new RestRequest("/sharing/rest/oauth2/token", Method.POST);

            restRequest.AddParameter("client_id", PublicApiKey);
            restRequest.AddParameter("code", authorizationCode);
            restRequest.AddParameter("redirect_uri", redirectUri.AbsoluteUri);
            restRequest.AddParameter("grant_type", "authorization_code");

            var restClient = RestClientFactory.CreateRestClient("https://www.arcgis.com/");

            TraceSource.TraceVerbose("Retrieving Access Token endpoint: {0}",
                                     restClient.BuildUri(restRequest).AbsoluteUri);

            // ArcGIS Online returns the token as text/plain, but it's actually a JSON payload
            restClient.AddHandler("text/plain", new RestSharp.Deserializers.JsonDeserializer());

            var response = restClient.Execute <AccessTokenResult>(restRequest);

            return(response);
        }
Exemple #6
0
        protected override IRestResponse <AccessTokenResult> ExecuteRetrieveAccessToken(string authorizationCode, Uri redirectUri)
        {
            if (string.IsNullOrEmpty(authorizationCode))
            {
                throw new ArgumentNullException("authorizationCode");
            }

            if (redirectUri == null ||
                string.IsNullOrEmpty(redirectUri.AbsoluteUri))
            {
                throw new ArgumentNullException("redirectUri");
            }

            var restRequest = new RestRequest("/oauth/access_token", Method.POST);

            restRequest.AddParameter("client_id", PublicApiKey);
            restRequest.AddParameter("client_secret", SecretApiKey);
            restRequest.AddParameter("redirect_uri", redirectUri.AbsoluteUri);
            restRequest.AddParameter("code", authorizationCode);
            restRequest.AddParameter("grant_type", "authorization_code");

            var restClient = RestClientFactory.CreateRestClient("https://api.instagram.com");

            return(restClient.Execute <AccessTokenResult>(restRequest));
        }
Exemple #7
0
 private void Initialize()
 {
     ServicePointManager.UseNagleAlgorithm = false;
     if (!ClassFactory.TryGet("EnrichmentServiceRestClient", out _restClient))
     {
         _restClient = RestClientFactory.CreateRestClient();
     }
 }
Exemple #8
0
 /// <summary>
 /// Initializes instance of proxy to email analysis web service.
 /// </summary>
 /// <param name="userConnection">The user connection.</param>
 public EmailMiningServiceProxy(UserConnection userConnection)
 {
     _userConnection = userConnection;
     if (!ClassFactory.TryGet("EmailMiningServiceProxyRestClient", out _httpClient))
     {
         _httpClient = RestClientFactory.CreateRestClient();
     }
 }
        protected override IRestResponse <AccessTokenResult> ExecuteRetrieveAccessToken(string authorizationCode,
                                                                                        Uri redirectUri)
        {
            if (string.IsNullOrEmpty(authorizationCode))
            {
                throw new ArgumentNullException("authorizationCode");
            }

            if (redirectUri == null ||
                string.IsNullOrEmpty(redirectUri.AbsoluteUri))
            {
                throw new ArgumentNullException("redirectUri");
            }

            var restRequest = new RestRequest("oauth/access_token");

            restRequest.AddParameter("client_id", PublicApiKey);
            restRequest.AddParameter("client_secret", SecretApiKey);
            restRequest.AddParameter("code", authorizationCode);
            restRequest.AddParameter("redirect_uri", redirectUri.AbsoluteUri.ToLowerInvariant());
            restRequest.AddHeader("Content-Type", "application/json");
            restRequest.AddParameter("format", "json");

            var restClient = RestClientFactory.CreateRestClient(BaseUrl);

            TraceSource.TraceVerbose("Retrieving Access Token endpoint: {0}",
                                     restClient.BuildUri(restRequest).AbsoluteUri);

            // Really really sad hack. Facebook send back all their data as Json except
            // this f'ing endpoint. As such, we'll f**k with things here.
            // We'll manually create the data - if possible.
            // How - we will try and recreate the content result.
            restRequest.OnBeforeDeserialization = response =>
            {
                // Grab the content and convert it into json.
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    // Something is wrong - so just leave. This is handled elsewhere.
                    return;
                }

                // Lets do this!
                var querystringData = HttpUtility.ParseQueryString(response.Content);
                var json            = new StringBuilder("{"); // Start.

                foreach (var key in querystringData.AllKeys)
                {
                    json.AppendFormat("\"{0}\":\"{1}\"", key, querystringData[key]);
                }

                json.Append("}"); // End.

                response.Content     = json.ToString();
                response.ContentType = "text/json";
            };

            return(restClient.Execute <AccessTokenResult>(restRequest));
        }
        protected override UserInformation RetrieveUserInformation(AccessToken accessToken)
        {
            if (accessToken == null)
            {
                throw new ArgumentNullException("accessToken");
            }

            if (string.IsNullOrEmpty(accessToken.PublicToken))
            {
                throw new ArgumentException("accessToken.PublicToken");
            }

            IRestResponse <UserInfoResult> response;

            try
            {
                var restRequest = new RestRequest("/user", Method.GET);
                restRequest.AddParameter(AccessTokenKey, accessToken.PublicToken);

                var restClient = RestClientFactory.CreateRestClient("https://api.github.com");
                TraceSource.TraceVerbose("Retrieving user information. GitHub Endpoint: {0}",
                                         restClient.BuildUri(restRequest).AbsoluteUri);

                response = restClient.Execute <UserInfoResult>(restRequest);
            }
            catch (Exception exception)
            {
                throw new AuthenticationException("Failed to obtain User Info from GitHub.", exception);
            }

            if (response == null ||
                response.StatusCode != HttpStatusCode.OK)
            {
                throw new AuthenticationException(
                          string.Format(
                              "Failed to obtain User Info from GitHub OR the the response was not an HTTP Status 200 OK. Response Status: {0}. Response Description: {1}",
                              response == null ? "-- null response --" : response.StatusCode.ToString(),
                              response == null ? string.Empty : response.StatusDescription));
            }

            // Lets check to make sure we have some bare minimum data.
            if (string.IsNullOrEmpty(response.Data.Id.ToString()) ||
                string.IsNullOrEmpty(response.Data.Login) ||
                string.IsNullOrEmpty(response.Data.Name))
            {
                throw new AuthenticationException(
                          "Retrieve some user info from the GitHub Api, but we're missing one or more of either: Id, Login, and Name.");
            }

            return(new UserInformation
            {
                Id = response.Data.Id.ToString(),
                Name = response.Data.Name,
                Email = response.Data.Email ?? "",
                Picture = response.Data.AvatarUrl,
                UserName = response.Data.Login
            });
        }
Exemple #11
0
 public void ServerHeaderShouldNotBeEmitted()
 {
     using (IRestClient client = RestClientFactory.CreateRestClient())
     {
         IRestClientResponse response = client.Get(WebAppUrl + "content/cached-by-max-age.txt").Do().Response;
         Assert.AreEqual((int)HttpStatusCode.OK, client.StatusCode);
         Assert.IsFalse(response.Headers.AllKeys.Any(x => x == HttpConsts.HeaderServer));
     }
 }
 public void CheckShortTextResponse()
 {
     using (IRestClient client = RestClientFactory.CreateRestClient())
     {
         IRestClientResponse response = client.Get(WebAppUrl + "stream/short-text").Do().Response;
         Assert.AreEqual((int)HttpStatusCode.OK, client.StatusCode);
         Assert.AreEqual("This is a stream response", response.AsString());
     }
 }
        private UserInfo RetrieveUserInfo(AuthenticatedToken reponse)
        {
            var userRequest = new RestRequest("/v5.0/me");
            var userClient  = RestClientFactory.CreateRestClient("https://apis.live.net");

            userRequest.AddParameter("access_token", reponse.AccessToken);

            return(userClient.Execute <UserInfo>(userRequest).Data);
        }
Exemple #14
0
        protected override UserInformation RetrieveUserInformation(AccessToken accessToken)
        {
            if (accessToken == null)
            {
                throw new ArgumentNullException("accessToken");
            }

            if (string.IsNullOrEmpty(accessToken.PublicToken))
            {
                throw new ArgumentException("accessToken.PublicToken");
            }

            IRestResponse <UserInfoResult> response;

            try
            {
                var restRequest = new RestRequest("/users/self", Method.GET);
                restRequest.AddParameter(AccessTokenKey, accessToken.PublicToken);
                var restClient = RestClientFactory.CreateRestClient("https://api.instagram.com/v1/");
                restClient.UserAgent = PublicApiKey;
                response             = restClient.Execute <UserInfoResult>(restRequest);
            }
            catch (Exception exception)
            {
                throw new AuthenticationException("Failed to obtain User Info from Instagram.", exception);
            }

            if (response == null ||
                response.StatusCode != HttpStatusCode.OK)
            {
                throw new AuthenticationException(
                          string.Format(
                              "Failed to obtain User Info from Instagram OR the the response was not an HTTP Status 200 OK. Response Status: {0}. Response Description: {1}",
                              response == null ? "-- null response --" : response.StatusCode.ToString(),
                              response == null ? string.Empty : response.StatusDescription));
            }

            // Lets check to make sure we have some bare minimum data.
            if (string.IsNullOrEmpty(response.Data.Data.Id) ||
                string.IsNullOrEmpty(response.Data.Data.Username))
            {
                throw new AuthenticationException(
                          string.Format(
                              "Retrieve some user info from the Instagram API, but we're missing one or both: Id: '{0}' and Username: '******'.",
                              string.IsNullOrEmpty(response.Data.Data.Id) ? "--missing--" : response.Data.Data.Id,
                              string.IsNullOrEmpty(response.Data.Data.Username) ? "--missing--" : response.Data.Data.Username));
            }

            return(new UserInformation
            {
                Id = response.Data.Data.Id,
                Name = response.Data.Data.FullName,
                Picture = response.Data.Data.ProfilePicture,
                UserName = response.Data.Data.Username
            });
        }
 public void CheckLongBinaryResponse()
 {
     using (IRestClient client = RestClientFactory.CreateRestClient())
     {
         IRestClientResponse response = client.Get(WebAppUrl + "stream/long-binary").Do().Response;
         Assert.AreEqual((int)HttpStatusCode.OK, client.StatusCode);
         byte[] bytes = response.AsBytes();
         Assert.AreEqual(4 * 1024 * 1024, bytes.Length);
     }
 }
        protected override UserInformation RetrieveUserInformation(AccessToken accessToken)
        {
            if (accessToken == null)
            {
                throw new ArgumentNullException("accessToken");
            }

            if (string.IsNullOrEmpty(accessToken.PublicToken))
            {
                throw new ArgumentException("accessToken.PublicToken");
            }

            IRestResponse <UserInfoResult> response;

            try
            {
                var restRequest = new RestRequest("/sharing/rest/community/self", Method.GET);
                restRequest.AddParameter(AccessTokenKey, accessToken.PublicToken);
                restRequest.AddParameter("f", "json");

                // ArcGIS Online returns the token as text/plain, but it's actually a JSON payload
                var restClient = RestClientFactory.CreateRestClient("https://www.arcgis.com");
                restClient.AddHandler("text/plain", new RestSharp.Deserializers.JsonDeserializer());
                restClient.UserAgent = PublicApiKey;

                TraceSource.TraceVerbose("Retrieving user information. ArcGIS Online Endpoint: {0}",
                                         restClient.BuildUri(restRequest).AbsoluteUri);

                response = restClient.Execute <UserInfoResult>(restRequest);
            }
            catch (Exception exception)
            {
                throw new AuthenticationException("Failed to obtain User Info from ArcGIS Online.", exception);
            }

            if (response == null ||
                response.StatusCode != HttpStatusCode.OK)
            {
                throw new AuthenticationException(
                          string.Format(
                              "Failed to obtain User Info from ArcGIS Online OR the the response was not an HTTP Status 200 OK. Response Status: {0}. Response Description: {1}",
                              response == null ? "-- null response --" : response.StatusCode.ToString(),
                              response == null ? string.Empty : response.StatusDescription));
            }

            return(new UserInformation
            {
                Id = response.Data.UserName,
                Name = response.Data.FullName,
                Email = response.Data.Email,
                UserName = response.Data.UserName
            });
        }
        private AccessTokenResult RetrieveAccessToken(string authorizationCode, Uri redirectUri)
        {
            if (string.IsNullOrEmpty(authorizationCode))
            {
                throw new ArgumentNullException("authorizationCode");
            }

            if (redirectUri == null ||
                string.IsNullOrEmpty(redirectUri.AbsoluteUri))
            {
                throw new ArgumentNullException("redirectUri");
            }

            IRestResponse <AccessTokenResult> response;

            try
            {
                var request = new RestRequest("/o/oauth2/token", Method.POST);
                request.AddParameter("client_id", _clientId);
                request.AddParameter("client_secret", _clientSecret);
                request.AddParameter("redirect_uri", redirectUri.AbsoluteUri);
                request.AddParameter("code", authorizationCode);
                request.AddParameter("grant_type", "authorization_code");
                var restClient = RestClientFactory.CreateRestClient("https://accounts.google.com");
                response = restClient.Execute <AccessTokenResult>(request);
            }
            catch (Exception exception)
            {
                throw new AuthenticationException("Failed to obtain an Access Token from Google.", exception);
            }

            if (response == null ||
                response.StatusCode != HttpStatusCode.OK)
            {
                throw new AuthenticationException(
                          string.Format(
                              "Failed to obtain an Access Token from Google OR the the response was not an HTTP Status 200 OK. Response Status: {0}. Response Description: {1}",
                              response == null ? "-- null response --" : response.StatusCode.ToString(),
                              response == null ? string.Empty : response.StatusDescription));
            }

            // Grab the params which should have the request token info.
            if (string.IsNullOrEmpty(response.Data.AccessToken) ||
                response.Data.ExpiresIn <= 0 ||
                string.IsNullOrEmpty(response.Data.TokenType))
            {
                throw new AuthenticationException(
                          "Retrieved a Google Access Token but it doesn't contain one or more of either: " + AccessTokenKey +
                          ", " + ExpiresInKey + " or " + TokenTypeKey);
            }

            return(response.Data);
        }
Exemple #18
0
        private AccessTokenResult RetrieveAccessToken(string authorizationCode, Uri redirectUri)
        {
            if (string.IsNullOrEmpty(authorizationCode))
            {
                throw new ArgumentNullException("authorizationCode");
            }

            if (redirectUri == null ||
                string.IsNullOrEmpty(redirectUri.AbsoluteUri))
            {
                throw new ArgumentNullException("redirectUri");
            }

            IRestResponse <AccessTokenResult> response;

            try
            {
                var request = new RestRequest("/uas/oauth2/accessToken", Method.POST);
                request.AddParameter("client_id", _clientId);
                request.AddParameter("client_secret", _clientSecret);
                request.AddParameter("redirect_uri", redirectUri.AbsoluteUri);
                request.AddParameter("code", authorizationCode);
                request.AddParameter("grant_type", "authorization_code");
                var restClient = RestClientFactory.CreateRestClient("https://www.linkedin.com");
                response = restClient.Execute <AccessTokenResult>(request);
            }
            catch (Exception exception)
            {
                throw new AuthenticationException("Failed to obtain an Access Token from LinkedIn. The connection to LinkedIn failed for some reason. Can you access LinkedIn manually via a browser?", exception);
            }

            if (response == null ||
                response.StatusCode != HttpStatusCode.OK)
            {
                throw new AuthenticationException(
                          string.Format(
                              "Failed to obtain an Access Token from LinkedIn OR the the response was not an HTTP Status 200 OK. Response Status: {0}. Response Description: {1}",
                              response == null ? "-- null response --" : response.StatusCode.ToString(),
                              response == null ? string.Empty : response.StatusDescription));
            }

            // Grab the params which should have the request token info.
            if (string.IsNullOrEmpty(response.Data.AccessToken) ||
                response.Data.ExpiresIn <= 0)
            {
                throw new AuthenticationException(
                          string.Format("Retrieved a LinkedIn Access Token but it doesn't contain one or more of either: {0} or {1} or the {1} value [{2}] needs to be greater than 0.",
                                        AccessTokenKey, ExpiresInKey, response.Data.ExpiresIn));
            }

            return(response.Data);
        }
        private AccessTokenResult RetrieveAccessToken(VerifierResult verifierResult)
        {
            if (verifierResult == null)
            {
                throw new ArgumentNullException("verifierResult");
            }

            if (string.IsNullOrEmpty(verifierResult.OAuthToken))
            {
                throw new ArgumentException("verifierResult.OAuthToken");
            }

            if (string.IsNullOrEmpty(verifierResult.OAuthToken))
            {
                throw new ArgumentException("verifierResult.OAuthVerifier");
            }

            IRestResponse response;

            try
            {
                var request    = new RestRequest("oauth/access_token", Method.POST);
                var restClient = RestClientFactory.CreateRestClient(BaseUrl);
                restClient.Authenticator = OAuth1Authenticator.ForAccessToken(_consumerKey, _consumerSecret,
                                                                              verifierResult.OAuthToken,
                                                                              null, verifierResult.OAuthVerifier);
                response = restClient.Execute(request);
            }
            catch (Exception exception)
            {
                throw new AuthenticationException("Failed to convert Request Token to an Access Token, from Twitter.",
                                                  exception);
            }

            if (response == null || response.StatusCode != HttpStatusCode.OK)
            {
                throw new AuthenticationException(
                          string.Format(
                              "Failed to obtain an Access Token from Twitter OR the the response was not an HTTP Status 200 OK. Response Status: {0}. Response Description: {1}",
                              response == null ? "-- null response --" : response.StatusCode.ToString(),
                              response == null ? string.Empty : response.StatusDescription));
            }

            var querystringParameters = HttpUtility.ParseQueryString(response.Content);

            return(new AccessTokenResult
            {
                AccessToken = querystringParameters[OAuthTokenKey],
                AccessTokenSecret = querystringParameters[OAuthTokenSecretKey]
            });
        }
Exemple #20
0
        private UserInformation RetrieveMe(string accessToken)
        {
            if (string.IsNullOrEmpty(accessToken))
            {
                throw new ArgumentNullException("accessToken");
            }

            IRestResponse <MeResult> response;

            try
            {
                var restRequest = new RestRequest("me");
                restRequest.AddParameter("access_token", accessToken);

                var restClient = RestClientFactory.CreateRestClient(BaseUrl);
                response = restClient.Execute <MeResult>(restRequest);
            }
            catch (Exception exception)
            {
                throw new AuthenticationException("Failed to retrieve any Me data from the Facebook Api.", exception);
            }

            if (response == null ||
                response.StatusCode != HttpStatusCode.OK ||
                response.Data == null)
            {
                throw new AuthenticationException(
                          string.Format(
                              "Failed to obtain some 'Me' data from the Facebook api OR the the response was not an HTTP Status 200 OK. Response Status: {0}. Response Description: {1}",
                              response == null ? "-- null response --" : response.StatusCode.ToString(),
                              response == null ? string.Empty : response.StatusDescription));
            }

            var id   = response.Data.Id < 0 ? 0 : response.Data.Id;
            var name = (string.IsNullOrEmpty(response.Data.FirstName)
                            ? string.Empty
                            : response.Data.FirstName) + " " +
                       (string.IsNullOrEmpty(response.Data.LastName)
                            ? string.Empty
                            : response.Data.LastName).Trim();

            return(new UserInformation
            {
                Id = id.ToString(),
                Name = name,
                Email = response.Data.Email,
                Locale = response.Data.Locale,
                UserName = response.Data.Username,
                Picture = string.Format("https://graph.facebook.com/{0}/picture", id)
            });
        }
        private AccessTokenResult RetrieveAccessToken(string authorizationCode, Uri redirectUri)
        {
            if (string.IsNullOrEmpty(authorizationCode))
            {
                throw new ArgumentNullException("authorizationCode");
            }

            if (redirectUri == null ||
                string.IsNullOrEmpty(redirectUri.AbsoluteUri))
            {
                throw new ArgumentNullException("redirectUri");
            }

            IRestResponse <AccessTokenResult> response;

            try
            {
                var request = new RestRequest("/auth/o2/token", Method.POST);

                request.AddParameter("client_id", _clientId);
                request.AddParameter("client_secret", _clientSecret);
                request.AddParameter("code", authorizationCode);
                request.AddParameter("grant_type", "authorization_code");
                request.AddParameter("redirect_uri", redirectUri);

                var restClient = RestClientFactory.CreateRestClient("https://api.amazon.com");
                response = restClient.Execute <AccessTokenResult>(request);
            }
            catch (Exception exception)
            {
                throw new AuthenticationException("Failed to obtain an Access Token from Amazon.", exception);
            }

            if (response == null ||
                response.StatusCode != HttpStatusCode.OK)
            {
                throw new AuthenticationException(
                          string.Format(
                              "Failed to obtain an Access Token from Amazon OR the the response was not an HTTP Status 200 OK. Response Status: {0}. Response Description: {1}",
                              response == null ? "-- null response --" : response.StatusCode.ToString(),
                              response == null ? string.Empty : response.StatusDescription));
            }

            if (string.IsNullOrEmpty(response.Data.AccessToken))
            {
                throw new AuthenticationException("AccessToken returned but was null or empty value");
            }

            return(response.Data);
        }
        private VerifyCredentialsResult VerifyCredentials(AccessTokenResult accessTokenResult)
        {
            if (accessTokenResult == null)
            {
                throw new ArgumentNullException("accessTokenResult");
            }

            if (string.IsNullOrEmpty(accessTokenResult.AccessToken))
            {
                throw new ArgumentException("accessTokenResult.AccessToken");
            }

            if (string.IsNullOrEmpty(accessTokenResult.AccessTokenSecret))
            {
                throw new ArgumentException("accessTokenResult.AccessTokenSecret");
            }

            IRestResponse <VerifyCredentialsResult> response;

            try
            {
                var restClient = RestClientFactory.CreateRestClient(BaseUrl);
                restClient.Authenticator = OAuth1Authenticator.ForProtectedResource(_consumerKey, _consumerSecret,
                                                                                    accessTokenResult.AccessToken,
                                                                                    accessTokenResult.AccessTokenSecret);
                var request = new RestRequest("1.1/account/verify_credentials.json");
                response = restClient.Execute <VerifyCredentialsResult>(request);
            }
            catch (Exception exception)
            {
                throw new AuthenticationException(
                          "Failed to retrieve VerifyCredentials json data from the Twitter Api.", exception);
            }

            if (response == null ||
                response.StatusCode != HttpStatusCode.OK ||
                response.Data == null)
            {
                throw new AuthenticationException(
                          string.Format(
                              "Failed to retrieve VerifyCredentials json data OR the the response was not an HTTP Status 200 OK. Response Status: {0}. Response Description: {1}",
                              response == null ? "-- null response --" : response.StatusCode.ToString(),
                              response == null ? string.Empty : response.StatusDescription));
            }

            return(response.Data);
        }
Exemple #23
0
        /// <summary>
        /// Initializes internal http client.
        /// </summary>
        /// <param name="serviceUrl"></param>
        protected virtual void InitHttpClient(string serviceUrl)
        {
            CheckRequiredSetting("MLProblemType.ServiceUrl", serviceUrl);
            if (ClassFactory.TryGet("MLServiceClient", out _httpClient))
            {
#if NETFRAMEWORK
                _httpClient.BaseUrl = serviceUrl;
#else
                _httpClient.BaseUrl = new Uri(serviceUrl);
#endif
            }
            else
            {
                _httpClient = RestClientFactory.CreateRestClient(serviceUrl);
            }
            _httpClient.AddDefaultHeader("ApiKey", _apiKey);
        }
        private UserInfoResult RetrieveUserInfo(string accessToken)
        {
            if (string.IsNullOrEmpty(accessToken))
            {
                throw new ArgumentNullException("accessToken");
            }

            IRestResponse <UserInfoResult> response;

            try
            {
                var request = new RestRequest("/user", Method.GET);
                request.AddParameter(AccessTokenKey, accessToken);

                var restClient = RestClientFactory.CreateRestClient("https://api.github.com");
                response = restClient.Execute <UserInfoResult>(request);
            }
            catch (Exception exception)
            {
                throw new AuthenticationException("Failed to obtain User Info from GitHub.", exception);
            }

            if (response == null ||
                response.StatusCode != HttpStatusCode.OK)
            {
                throw new AuthenticationException(
                          string.Format(
                              "Failed to obtain User Info from GitHub OR the the response was not an HTTP Status 200 OK. Response Status: {0}. Response Description: {1}",
                              response == null ? "-- null response --" : response.StatusCode.ToString(),
                              response == null ? string.Empty : response.StatusDescription));
            }

            // Lets check to make sure we have some bare minimum data.
            if (string.IsNullOrEmpty(response.Data.Id.ToString()) ||
                string.IsNullOrEmpty(response.Data.Login) ||
                string.IsNullOrEmpty(response.Data.Name))
            {
                throw new AuthenticationException(
                          "Retrieve some user info from the GitHub Api, but we're missing one or more of either: Id, Login, and Name.");
            }

            return(response.Data);
        }
        private UserInfoResult RetrieveUserInfo(string accessToken)
        {
            if (string.IsNullOrEmpty(accessToken))
            {
                throw new ArgumentNullException("accessToken");
            }

            IRestResponse <UserInfoResult> response;

            try
            {
                var request = new RestRequest("/oauth2/v2/userinfo", Method.GET);
                request.AddParameter(AccessTokenKey, accessToken);

                var restClient = RestClientFactory.CreateRestClient("https://www.googleapis.com");
                response = restClient.Execute <UserInfoResult>(request);
            }
            catch (Exception exception)
            {
                throw new AuthenticationException("Failed to obtain User Info from Google.", exception);
            }

            if (response == null ||
                response.StatusCode != HttpStatusCode.OK)
            {
                throw new AuthenticationException(
                          string.Format(
                              "Failed to obtain User Info from Google OR the the response was not an HTTP Status 200 OK. Response Status: {0}. Response Description: {1}",
                              response == null ? "-- null response --" : response.StatusCode.ToString(),
                              response == null ? string.Empty : response.StatusDescription));
            }

            // Lets check to make sure we have some bare minimum data.
            if (string.IsNullOrEmpty(response.Data.Id))
            {
                throw new AuthenticationException(
                          "We were unable to retrieve the User Id from Google API, the user may have denied the authorization.");
            }

            return(response.Data);
        }
        public Uri RedirectToAuthenticate(IAuthenticationServiceSettings authenticationServiceSettings)
        {
            if (authenticationServiceSettings == null)
            {
                throw new ArgumentNullException("authenticationServiceSettings");
            }

            if (authenticationServiceSettings.CallBackUri == null)
            {
                throw new ArgumentException("authenticationServiceSettings.CallBackUri");
            }

            // First we need to grab a request token.
            var oAuthToken = RetrieveRequestToken(authenticationServiceSettings);

            // Now we need the user to enter their name/password/accept this app @ Twitter.
            // This means we need to redirect them to the Twitter website.
            var request = new RestRequest("oauth/authenticate");

            request.AddParameter(OAuthTokenKey, oAuthToken.OAuthToken);
            var restClient = RestClientFactory.CreateRestClient(BaseUrl);

            return(restClient.BuildUri(request));
        }
        private AuthenticatedToken RetrieveToken(NameValueCollection queryStringParameters, Uri redirectUri)
        {
            if (queryStringParameters == null)
            {
                throw new ArgumentNullException();
            }

            if (redirectUri == null ||
                string.IsNullOrEmpty(redirectUri.AbsoluteUri))
            {
                throw new ArgumentNullException();
            }

            var request = new RestRequest("/oauth20_token.srf");
            var client  = RestClientFactory.CreateRestClient("https://login.live.com/oauth20_token.srf");

            request.AddParameter("client_id", _clientId);
            request.AddParameter("redirect_uri", redirectUri);
            request.AddParameter("client_secret", _clientSecret);
            request.AddParameter("code", queryStringParameters["code"]);
            request.AddParameter("grant_type", "authorization_code");

            return(client.Execute <AuthenticatedToken>(request).Data);
        }
        protected override UserInformation RetrieveUserInformation(AccessToken accessToken)
        {
            if (accessToken == null)
            {
                throw new ArgumentNullException("accessToken");
            }

            if (string.IsNullOrEmpty(accessToken.PublicToken))
            {
                throw new ArgumentException("accessToken.PublicToken");
            }

            IRestResponse <UserInfoResult> response;

            try
            {
                var restRequest = new RestRequest("/v5.0/me");
                restRequest.AddParameter(AccessTokenKey, accessToken.PublicToken);

                var restClient = RestClientFactory.CreateRestClient("https://apis.live.net");
                TraceSource.TraceVerbose("Retrieving user information. Microsoft Live Endpoint: {0}",
                                         restClient.BuildUri(restRequest).AbsoluteUri);

                response = restClient.Execute <UserInfoResult>(restRequest);
            }
            catch (Exception exception)
            {
                var errorMessage =
                    string.Format("Failed to retrieve any Me data from the Microsoft Live api. Error Messages: {0}",
                                  exception.RecursiveErrorMessages());
                TraceSource.TraceError(errorMessage);
                throw new AuthenticationException(errorMessage, exception);
            }

            if (response == null ||
                response.StatusCode != HttpStatusCode.OK)
            {
                var errorMessage = string.Format(
                    "Failed to obtain some 'Me' data from the Microsoft Live api OR the the response was not an HTTP Status 200 OK. Response Status: {0}. Response Description: {1}. Error Message: {2}.",
                    response == null ? "-- null response --" : response.StatusCode.ToString(),
                    response == null ? string.Empty : response.StatusDescription,
                    response == null
                        ? string.Empty
                        : response.ErrorException == null
                              ? "--no error exception--"
                              : response.ErrorException.RecursiveErrorMessages());

                TraceSource.TraceError(errorMessage);
                throw new AuthenticationException(errorMessage);
            }

            // Lets check to make sure we have some bare minimum data.
            if (string.IsNullOrEmpty(response.Data.id))
            {
                const string errorMessage =
                    "We were unable to retrieve the User Id from Windows Live Api, the user may have denied the authorization.";
                TraceSource.TraceError(errorMessage);
                throw new AuthenticationException(errorMessage);
            }

            return(new UserInformation
            {
                Name = string.Format("{0} {1}",
                                     string.IsNullOrEmpty(response.Data.first_name)
                                                ? string.Empty
                                                : response.Data.first_name,
                                     string.IsNullOrEmpty(response.Data.last_name)
                                                ? string.Empty
                                                : response.Data.last_name).Trim(),
                Locale = response.Data.locale,
                UserName = response.Data.name,
                Id = response.Data.id,
                Email = response.Data.emails.Preferred,
                Gender = (GenderType)Enum.Parse(typeof(GenderType), response.Data.gender ?? "Unknown", true)
            });
        }
Exemple #29
0
        private UserInformation ExtractUserInformationFromBasecamp(Account account, AccessToken accessToken)
        {
            if (account == null)
            {
                throw new ArgumentNullException("account");
            }

            if (accessToken == null)
            {
                throw new ArgumentNullException("accessToken");
            }

            IRestResponse <PersonResult> response;

            try
            {
                var restRequest = new RestRequest(account.Id + "/api/v1/people/me.json", Method.GET);
                restRequest.AddParameter("access_token", accessToken.PublicToken);
                restRequest.AddHeader("User-Agent",
                                      "SimpleAuthentication .NET Library. (http://www.github.com/simpleauthentication");

                var restClient = RestClientFactory.CreateRestClient(account.Href);

                TraceSource.TraceVerbose("Retrieving person/me.json data. 37 Signals Endpoint: {0}",
                                         restClient.BuildUri(restRequest).AbsoluteUri);

                // Reference Uri: {https://streetadvisor.basecamphq.com/772576/api/v1/people/me.json?access_token=BAhbByIByHsiZXhwaXJlc19hdCI6IjIwMTMtMDctMjBUMjM6NDc6NTRaIiwidXNlcl9pZHMiOls0NjE2OTUxLDY1NTgwNjUsODYyNDEwNywxMTc2MzU5NV0sImNsaWVudF9pZCI6ImFkZDMyZjZhYTJkNjJmNjUwMzEyY2ExOGM5MDhhYWMyMWE0NzNmMGIiLCJ2ZXJzaW9uIjoxLCJhcGlfZGVhZGJvbHQiOiIwMzY0ZTFmYjk3ZjI3MDEzNThhYjIwYzg5OWJjMGY5MCJ9dToJVGltZQ2XWhzABM1tvw==--f2ad7f5706d2e9c45e2c6dc1f32b5e62db2e56fc}

                response = restClient.Execute <PersonResult>(restRequest);
            }
            catch (Exception exception)
            {
                var errorMessage =
                    string.Format(
                        "Failed to retrieve any Person/me.json data from the 37 Signals Api. Error Messages: {0}",
                        exception.RecursiveErrorMessages());
                TraceSource.TraceError(errorMessage);
                throw new AuthenticationException(errorMessage, exception);
            }

            if (response == null ||
                response.StatusCode != HttpStatusCode.OK)
            {
                var errorMessage = string.Format(
                    "Failed to obtain some person/me.json data from the 37 Signals Api OR the the response was not an HTTP Status 200 OK. Response Status: {0}. Response Description: {1}. Error Message: {2}.",
                    response == null ? "-- null response --" : response.StatusCode.ToString(),
                    response == null ? string.Empty : response.StatusDescription,
                    response == null
                        ? string.Empty
                        : response.ErrorException == null
                              ? "--no error exception--"
                              : response.ErrorException.RecursiveErrorMessages());

                TraceSource.TraceError(errorMessage);
                throw new AuthenticationException(errorMessage);
            }

            return(new UserInformation
            {
                Email = response.Data.email_address,
                Id = response.Data.identity_id,
                Name = response.Data.Name,
                Picture = response.Data.avatar_url
            });
        }
Exemple #30
0
        protected override UserInformation RetrieveUserInformation(AccessToken accessToken)
        {
            if (accessToken == null)
            {
                throw new ArgumentNullException("accessToken");
            }

            if (string.IsNullOrEmpty(accessToken.PublicToken))
            {
                throw new ArgumentException("accessToken.PublicToken");
            }

            IRestResponse <UserInfoResult> response;

            try
            {
                var restRequest = new RestRequest("/authorization.json", Method.GET);
                restRequest.AddParameter("access_token", accessToken.PublicToken);

                var restClient = RestClientFactory.CreateRestClient("https://launchpad.37signals.com");

                TraceSource.TraceVerbose("Retrieving user information. 37 Signals Endpoint: {0}",
                                         restClient.BuildUri(restRequest).AbsoluteUri);

                response = restClient.Execute <UserInfoResult>(restRequest);
            }
            catch (Exception exception)
            {
                var errorMessage =
                    string.Format("Failed to retrieve any UserInfo data from the 37 Signals Api. Error Messages: {0}",
                                  exception.RecursiveErrorMessages());
                TraceSource.TraceError(errorMessage);
                throw new AuthenticationException(errorMessage, exception);
            }

            if (response == null ||
                response.StatusCode != HttpStatusCode.OK)
            {
                var errorMessage = string.Format(
                    "Failed to obtain some UserInfo data from the 37 Signals Api OR the the response was not an HTTP Status 200 OK. Response Status: {0}. Response Description: {1}. Error Message: {2}.",
                    response == null ? "-- null response --" : response.StatusCode.ToString(),
                    response == null ? string.Empty : response.StatusDescription,
                    response == null
                        ? string.Empty
                        : response.ErrorException == null
                              ? "--no error exception--"
                              : response.ErrorException.RecursiveErrorMessages());

                TraceSource.TraceError(errorMessage);
                throw new AuthenticationException(errorMessage);
            }

            // Lets check to make sure we have some bare minimum data.
            if (response.Data.Identity == null ||
                string.IsNullOrEmpty(response.Data.Identity.Id))
            {
                const string errorMessage =
                    "We were unable to retrieve the User Id from 37 Signals Api, the user may have denied the authorization.";
                TraceSource.TraceError(errorMessage);
                throw new AuthenticationException(errorMessage);
            }

            UserInformation userInformation = null;

            //if (response.Data.Accounts != null &&
            //    response.Data.Accounts.Count > 0)
            //{
            //    userInformation = ExtractUserInformationFromProject(response.Data.Accounts[0], accessToken);
            //}

            return(userInformation ?? (new UserInformation
            {
                Id = response.Data.Identity.Id,
                Gender = GenderType.Unknown,
                Name =
                    string.Format("{0} {1}",
                                  response.Data.Identity.First_name ?? string.Empty,
                                  response.Data.Identity.Last_name ?? string.Empty),
                Email = response.Data.Identity.Email_address
            }));
        }