Exemplo n.º 1
0
        public void RequestForAccessToken(TRANSPORT_METHOD method = TRANSPORT_METHOD.GET)
        {
            if (method != TRANSPORT_METHOD.GET && method != TRANSPORT_METHOD.POST)
            {
                throw new OAuthException("Invalid Verb used for requesting AccessToken. Supported verbs are GET/POST.");
            }

            UriBuilder ub = new UriBuilder(provider.AccessTokenEndpoint);
            //logger.LogAuthorizationRequest(ub.ToString());
            HttpWebRequest request;

            if (method == TRANSPORT_METHOD.POST)
            {
                request = (HttpWebRequest)WebRequest.Create(ub.ToString());
                string postData = "code=" + ConnectionToken.Code;
                postData += ("&client_id=" + provider.Consumerkey);
                postData += ("&client_secret=" + provider.Consumersecret);
                postData += ("&redirect_uri=" + ConnectionToken.ProviderCallbackUrl);
                postData += ("&grant_type=authorization_code");

                request.Method = "POST";
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                // Set the ContentType property of the WebRequest.
                request.ContentType = "application/x-www-form-urlencoded";
                // Set the ContentLength property of the WebRequest.
                request.ContentLength = byteArray.Length;
                // Get the request stream.
                Stream dataStream = request.GetRequestStream();
                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);
                // Close the Stream object.
                dataStream.Close();
                // Get the response.
            }
            else
            {
                ub.SetQueryparameter("client_id", provider.Consumerkey);
                ub.SetQueryparameter("client_secret", provider.Consumersecret);
                ub.SetQueryparameter("code", ConnectionToken.Code);
                ub.SetQueryparameter("redirect_uri", ConnectionToken.ProviderCallbackUrl);
                ub.SetQueryparameter("grant_type", "authorization_code");

                request        = (HttpWebRequest)WebRequest.Create(ub.ToString());
                request.Method = "POST";
            }


            try
            {
                logger.Debug("Requesting Access Token at " + ub.ToString());
                using (HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse())
                    using (Stream responseStream = webResponse.GetResponseStream())
                        using (StreamReader reader = new StreamReader(responseStream))
                        {
                            string authToken = reader.ReadToEnd();
                            HandleAccessTokenResponse(authToken);
                        }
            }
            catch (Exception ex)
            {
                logger.Error(ErrorMessages.AccessTokenRequestError(request.RequestUri.ToString(), new QueryParameters()), ex);
                throw new OAuthException(ErrorMessages.AccessTokenRequestError(request.RequestUri.ToString(), new QueryParameters()), ex);
            }
        }
Exemplo n.º 2
0
        public override System.Net.WebResponse ExecuteFeed(string feedURL, IProvider provider, BusinessObjects.Token connectionToken, BusinessObjects.TRANSPORT_METHOD transportMethod, byte[] content = null, Dictionary <string, string> headers = null)
        {
            string      signature   = "";
            OAuthHelper oauthHelper = new OAuthHelper();


            string          timestamp   = oauthHelper.GenerateTimeStamp();
            QueryParameters oauthParams = new QueryParameters();

            oauthParams.Add("oauth_consumer_key", provider.Consumerkey);
            oauthParams.Add("oauth_nonce", oauthHelper.GenerateNonce());
            oauthParams.Add("oauth_signature_method", provider.SignatureMethod.ToString());
            oauthParams.Add("oauth_timestamp", timestamp);
            oauthParams.Add("oauth_token", connectionToken.AccessToken);
            oauthParams.Add("oauth_version", "1.0");
            signature = oauthHelper.GenerateSignature(new Uri(feedURL), oauthParams, provider.Consumerkey, provider.Consumersecret, provider.SignatureMethod, TRANSPORT_METHOD.POST, connectionToken.TokenSecret);



            oauthParams.Add("oauth_signature", signature);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(feedURL);

            request.Method = transportMethod.ToString();
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    switch (header.Key.ToLower())
                    {
                    case "contentlength":
                    {
                        request.ContentLength = long.Parse(header.Value);
                        break;
                    }

                    case "contenttype":
                    {
                        request.ContentType = header.Value;
                        break;
                    }

                    default:
                    {
                        request.Headers[header.Key] = header.Value;
                        break;
                    }
                    }
                }
            }

            request.ContentLength = (content == null) ? 0 : content.Length;
            request.Headers.Add("Authorization", oauthHelper.GetAuthorizationHeader(oauthParams));
            if (content != null)
            {
                request.GetRequestStream().Write(content, 0, content.Length);
            }
            WebResponse wr = null;

            try
            {
                logger.Debug("Executing " + feedURL + " using " + transportMethod.ToString() + Environment.NewLine + "Request Parameters: " + oauthParams.ToString());
                wr = (WebResponse)request.GetResponse();
                logger.Info("Successfully executed  " + feedURL + " using " + transportMethod.ToString());
            }
            catch (Exception ex)
            {
                logger.Error(ErrorMessages.CustomFeedExecutionError(feedURL, oauthParams), ex);
                throw new OAuthException(ErrorMessages.CustomFeedExecutionError(feedURL, oauthParams), ex);
            }
            return(wr);
        }
Exemplo n.º 3
0
        public void RequestForRequestToken()
        {
            QueryParameters oauthParameters = new QueryParameters();
            string          signature       = "";
            OAuthHelper     oauthHelper     = new OAuthHelper();


            //Twitter Test @ https://dev.twitter.com/docs/auth/oauth
            //oauthParameters.Add("oauth_callback", "http://localhost:3005/the_dance/process_callback?service_provider_id=11");
            //oauthParameters.Add("oauth_consumer_key", "GDdmIQH6jhtmLUypg82g");
            //oauthParameters.Add("oauth_nonce", "QP70eNmVz8jvdPevU3oJD2AfF7R7odC2XJcn4XlZJqk");
            //oauthParameters.Add("oauth_signature_method", "HMAC-SHA1");
            //oauthParameters.Add("oauth_timestamp", "1272323042");
            //oauthParameters.Add("oauth_version", "1.0");
            //signature = oauthHelper.GenerateSignature(new Uri(provider.RequestTokenEndpoint), oauthParameters, "GDdmIQH6jhtmLUypg82g", "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98", provider.SignatureMethod, provider.TransportName, string.Empty);

            ////1. Setup request parameters
            oauthParameters.Add("oauth_consumer_key", provider.Consumerkey);
            oauthParameters.Add("oauth_signature_method", provider.SignatureMethod.ToString());
            oauthParameters.Add("oauth_timestamp", oauthHelper.GenerateTimeStamp());
            oauthParameters.Add("oauth_nonce", oauthHelper.GenerateNonce());
            oauthParameters.Add("oauth_version", "1.0");
            oauthParameters.Add("oauth_callback", ConnectionToken.Domain + "SocialAuth/validate.sauth");

            //2. Notify Consumer (optionally user may wish to add extra parameters)
            BeforeRequestingRequestToken(oauthParameters); // hook called

            oauthParameters.ToList().ForEach(x => x.Value = Utility.UrlEncode(x.Value));

            //3. Generate Signature
            signature = oauthHelper.GenerateSignature(new Uri(provider.RequestTokenEndpoint), oauthParameters, provider.Consumerkey, provider.Consumersecret, provider.SignatureMethod, provider.TransportName, string.Empty);
            oauthParameters.Add("oauth_signature", signature);


            //4.Connect and obtain Token
            logger.Debug("Requesting Request Token at: " + provider.RequestTokenEndpoint);
            string         requestUrl = provider.RequestTokenEndpoint + "?" + oauthHelper.GetAuthorizationUrlParameters(oauthParameters);
            HttpWebRequest request    = (HttpWebRequest)HttpWebRequest.Create(requestUrl);

            request.Method = provider.TransportName.ToString();
            //request.Headers.Add("Authorization", oauthHelper.GetAuthorizationHeader(oauthParameters));
            request.ContentLength = 0;
            //request.ContentType = "application/x-www-form-urlencoded";
            //TODO: Check issue with Authorization Header
            string response = "";

            try
            {
                logger.Debug("Requesting Request Token at: " + provider.RequestTokenEndpoint);
                using (HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse())
                    using (Stream responseStream = webResponse.GetResponseStream())
                        using (StreamReader reader = new StreamReader(responseStream))
                        {
                            response = reader.ReadToEnd();
                            if (response.Contains("oauth_token_secret"))
                            {
                                logger.Debug("Request Token response: " + response.ToString());
                                var responseCollection = Utility.GetQuerystringParameters(response);
                                HandleRequestTokenGrant(responseCollection);
                            }
                        }
            }
            catch (Exception ex)
            {
                logger.Error(ErrorMessages.RequestTokenRequestError(provider.RequestTokenEndpoint, oauthParameters), ex);
                throw new OAuthException(ErrorMessages.RequestTokenRequestError(provider.RequestTokenEndpoint, oauthParameters), ex);
            }
        }
Exemplo n.º 4
0
        public void HandleRequestToken(QueryParameters responseCollection)
        {
            //In Hybrid protocol, OAuth may not be necessary. In such case flow ends
            //But some providers may have scope black as scope is defined at provider directly (like Yahoo)

            if (responseCollection.HasName("openid.mode"))
            {
                if (responseCollection["openid.mode"].Contains("cancel"))
                {
                    throw new UserDeniedPermissionException(provider.ProviderType);
                }
            }

            if (!string.IsNullOrEmpty(provider.GetScope()) || provider.IsScopeDefinedAtProvider)
            {
                if (responseCollection.HasName("openid.oauth.request_token"))
                {
                    ConnectionToken.RequestToken = responseCollection["openid.oauth.request_token"];
                }
                else if (responseCollection.HasName("openid.ext2.request_token"))
                {
                    ConnectionToken.RequestToken = responseCollection["openid.ext2.request_token"];
                }
                else
                {
                    logger.Error(ErrorMessages.RequestTokenResponseInvalid(responseCollection));
                    throw new OAuthException(ErrorMessages.RequestTokenResponseInvalid(responseCollection));
                }
            }
            QueryParameters openIDValues = new QueryParameters();

            if (responseCollection.HasName("openid.ns.ext1"))
            {
                if (responseCollection.HasName("openid.ext1.value.email"))
                {
                    openIDValues.Add(new QueryParameter("openid.ext1.value.email", responseCollection["openid.ext1.value.email"]));
                }
                if (responseCollection.HasName("openid.ext1.value.firstname"))
                {
                    openIDValues.Add(new QueryParameter("openid.ext1.value.firstname", responseCollection["openid.ext1.value.firstname"]));
                }
                if (responseCollection.HasName("openid.ext1.value.lastname"))
                {
                    openIDValues.Add(new QueryParameter("openid.ext1.value.lastname", responseCollection["openid.ext1.value.lastname"]));
                }
                if (responseCollection.HasName("openid.ext1.value.language"))
                {
                    openIDValues.Add(new QueryParameter("openid.ext1.value.language", responseCollection["openid.ext1.value.language"]));
                }
                if (responseCollection.HasName("openid.ext1.value.country"))
                {
                    openIDValues.Add(new QueryParameter("openid.ext1.value.country", responseCollection["openid.ext1.value.country"]));
                }
                if (responseCollection.HasName("openid.identity"))
                {
                    openIDValues.Add(new QueryParameter("openid.identity", responseCollection["openid.identity"]));
                }
                ConnectionToken.ResponseCollection.AddRange(openIDValues, true);
            }
            else if (responseCollection.HasName("openid.ns.ax"))
            {
                if (responseCollection.HasName("openid.ax.value.email"))
                {
                    openIDValues.Add(new QueryParameter("openid.ax.value.email", responseCollection["openid.ax.value.email"]));
                }
                if (responseCollection.HasName("openid.ax.value.firstname"))
                {
                    openIDValues.Add(new QueryParameter("openid.ax.value.firstname", responseCollection["openid.ax.value.firstname"]));
                }
                if (responseCollection.HasName("openid.ax.value.lastname"))
                {
                    openIDValues.Add(new QueryParameter("openid.ax.value.lastname", responseCollection["openid.ax.value.lastname"]));
                }
                if (responseCollection.HasName("openid.ax.value.language"))
                {
                    openIDValues.Add(new QueryParameter("openid.ax.value.language", responseCollection["openid.ax.value.language"]));
                }
                if (responseCollection.HasName("openid.ax.value.country"))
                {
                    openIDValues.Add(new QueryParameter("openid.ax.value.country", responseCollection["openid.ax.value.country"]));
                }
                ConnectionToken.ResponseCollection.AddRange(openIDValues, true);
            }
            logger.Info("User successfully logged in and returned with Authorization Token");
        }