Exemple #1
0
        public bool ValidateReturnValue(string verifier)
        {
            // 2. Exchange auth.token for access.token
            var result = TwitterWebRequest.PerformRequest(new Uri("https://api.twitter.com/oauth/access_token?callback_token=" + verifier),
                                                          ChannelHelper.ConsumerKey, ChannelHelper.ConsumerSecret, Token, TokenSecret, verifier);

            var parts = NameValueParser.GetCollection(result, "&");

            if (ChannelContext.Current == null)
            {
                throw new ArgumentNullException("ChannelContext.Current");
            }

            // Remove token from session
            SafeSession.Current.Remove("/Channels/Twitter/Redirect/Token");
            SafeSession.Current.Remove("/Channels/Twitter/Redirect/TokenSecret");

            // 7. Save auth keys
            ChannelContext.Current.ClientContext.SaveSetting("/Channels/Twitter/AuthToken", parts["oauth_token"]);
            ChannelContext.Current.ClientContext.SaveSetting("/Channels/Twitter/AuthSecret", parts["oauth_token_secret"]);

            Token       = parts["oauth_token"];
            TokenSecret = parts["oauth_token_secret"];

            username = parts["screen_name"];

            return(true);
        }
        public bool ValidateReturnValue(string returnValue)
        {
            var queryParams = NameValueParser.GetCollection(new Uri(returnValue).Query, "?", "&");

            if (queryParams["session"] == null)
            {
                return(false);
            }

            JObject result = JObject.Parse(HttpUtility.UrlDecode(queryParams["session"]));

            if (result["session_key"] == null || result["secret"] == null)
            {
                return(false);
            }

            Token       = result["session_key"].Value <string>();
            TokenSecret = result["secret"].Value <string>();

            if (ChannelContext.Current != null && ChannelContext.Current.ClientContext != null)
            {
                // 7. Save auth keys
                ChannelContext.Current.ClientContext.SaveSetting("/Channels/Facebook/SessionKey", Token);
                ChannelContext.Current.ClientContext.SaveSetting("/Channels/Facebook/SessionSecret", TokenSecret);
            }

            return(true);
        }
Exemple #3
0
        public bool ValidateReturnValue(string verifier)
        {
            var result = LinkedInWebRequest.PerformRequest(new Uri("https://api.linkedin.com/uas/oauth/accessToken"),
                                                           ChannelHelper.ConsumerKey, ChannelHelper.ConsumerSecret, Token, TokenSecret, verifier);

            var parts = NameValueParser.GetCollection(result, "&");

            if (ChannelContext.Current == null)
            {
                throw new ArgumentNullException("ChannelContext.Current");
            }

            // Remove token from session
            SafeSession.Current.Remove("/Channels/LinkedIn/Redirect/Token");
            SafeSession.Current.Remove("/Channels/LinkedIn/Redirect/TokenSecret");

            // 7. Save auth keys
            ChannelContext.Current.ClientContext.SaveSetting("/Channels/LinkedIn/AuthToken", parts["oauth_token"]);
            ChannelContext.Current.ClientContext.SaveSetting("/Channels/LinkedIn/AuthSecret", parts["oauth_token_secret"]);

            Token       = parts["oauth_token"];
            TokenSecret = parts["oauth_token_secret"];

            return(true);
        }
        public IAuthenticationUser Authenticate(IRequest request)
        {
            var authHeader = request.Headers["Authorization"];

            if (authHeader == null)
            {
                return(null);
            }


            if (_timer == null)
            {
                lock (Nonces)
                {
                    if (_timer == null)
                    {
                        _timer = new Timer(ManageNonces, null, 15000, 15000);
                    }
                }
            }

            var parser     = new NameValueParser();
            var parameters = new ParameterCollection();

            parser.Parse(authHeader.Value.Remove(0, AuthenticationScheme.Length + 1), parameters);
            if (!IsValidNonce(parameters["nonce"]) && !DisableNonceCheck)
            {
                throw new HttpException(HttpStatusCode.Unauthorized, "Invalid nonce.");
            }

            // request authentication information
            var username = parameters["username"];
            var user     = _userService.Lookup(username, request.Uri);

            if (user == null)
            {
                return(null);
            }

            // Encode authentication info
            var ha1 = string.IsNullOrEmpty(user.HA1) ? GetHa1(_realmRepository.GetRealm(request), username, user.Password) : user.HA1;

            // encode challenge info
            var a2           = String.Format("{0}:{1}", request.Method, request.Uri.AbsolutePath);
            var ha2          = GetMd5HashBinHex(a2);
            var hashedDigest = Encrypt(ha1, ha2, parameters["qop"],
                                       parameters["nonce"], parameters["nc"], parameters["cnonce"]);

            //validate
            if (parameters["response"] == hashedDigest)
            {
                return(user);
            }

            return(null);
        }
        public IAuthenticationUser Authenticate(IRequest request)
        {
            var authHeader = request.Headers["Authorization"];

            if (authHeader == null)
            {
                return(null);
            }


            var parser     = new NameValueParser();
            var parameters = new ParameterCollection();

            parser.Parse(authHeader.Value.Remove(0, this.AuthenticationScheme.Length + 1), parameters);

            var nc = int.Parse(parameters["nc"], NumberStyles.AllowHexSpecifier);

            if (!this.nonceService.IsValid(parameters["nonce"], nc) && !DisableNonceCheck)
            {
                throw new HttpException(HttpStatusCode.Forbidden, "Invalid nonce/nc.");
            }

            // request authentication information
            var username = parameters["username"];
            var user     = this.userService.Lookup(username, request.Uri);

            if (user == null)
            {
                return(null);
            }

            var uri = parameters["uri"];
            // Encode authentication info
            var ha1 = string.IsNullOrEmpty(user.Ha1)
                          ? GetHa1(this.realmRepository.GetRealm(request), username, user.Password)
                          : user.Ha1;

            // encode challenge info
            var a2           = String.Format("{0}:{1}", request.Method, uri);
            var ha2          = GetMd5HashBinHex(a2);
            var hashedDigest = this.Encrypt(ha1, ha2, parameters["qop"],
                                            parameters["nonce"], parameters["nc"], parameters["cnonce"]);

            //validate
            if (parameters["response"] == hashedDigest)
            {
                return(user);
            }

            return(null);
        }
        static string BuildOAuthParams(Uri source, string consumerKey, string consumerSecret, string token, string tokenSecret, string verifier, string httpMethod)
        {
            OAuthBase oauth = new OAuthBase();

            string timeStamp = OAuthBase.GenerateTimeStamp();
            string nonce     = OAuthBase.GenerateNonce();

            // Calling source.Query returns an urlencoded string, but we don't want that since we will use
            // oauth.UrlEncode ourselves
            var query      = HttpUtility.UrlDecode(source.Query.Contains("?") ? source.Query.Remove(0, 1) : source.Query);
            var parameters = NameValueParser.GetCollection(query, "&");

            parameters.Add("oauth_nonce", nonce);
            parameters.Add("oauth_signature_method", "HMAC-SHA1");

            parameters.Add("oauth_timestamp", timeStamp);
            parameters.Add("oauth_consumer_key", consumerKey);

            if (!String.IsNullOrEmpty(token))
            {
                parameters.Add("oauth_token", token);
            }

            if (!String.IsNullOrEmpty(verifier))
            {
                parameters.Add("oauth_verifier", verifier);
            }

            parameters.Add("oauth_version", "1.0");

            StringBuilder requestBuilder = new StringBuilder();

            string signature = oauth.GenerateSignature(source, parameters, consumerKey, consumerSecret, token, tokenSecret, httpMethod, timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1);

            parameters.Add("oauth_signature", signature);

            requestBuilder.Append("OAuth ");

            foreach (string key in parameters)
            {
                requestBuilder.Append(key);
                requestBuilder.Append("=");
                requestBuilder.Append(@"""" + OAuthBase.UrlEncode(parameters[key]) + @"""");

                requestBuilder.Append(", ");
            }

            return(requestBuilder.ToString());
        }
Exemple #7
0
        public Uri BuildRedirectUri()
        {
            var result = TwitterWebRequest.PerformRequest(new Uri("http://api.twitter.com/oauth/request_token"),
                                                          ChannelHelper.ConsumerKey, ChannelHelper.ConsumerSecret);
            var parts = NameValueParser.GetCollection(result, "&");

            Token       = parts["oauth_token"];
            TokenSecret = parts["oauth_token_secret"];

            // Save data in session for re-materialization
            SafeSession.Current["/Channels/Twitter/Redirect/Token"]       = Token;
            SafeSession.Current["/Channels/Twitter/Redirect/TokenSecret"] = TokenSecret;

            return(new Uri("https://api.twitter.com/oauth/authorize?oauth_token=" + Token));
        }
Exemple #8
0
        public Uri BuildRedirectUri()
        {
            // 1. Get Auth Token
            var result = LinkedInWebRequest.PerformRequest(new Uri("https://api.linkedin.com/uas/oauth/requestToken"),
                                                           ChannelHelper.ConsumerKey, ChannelHelper.ConsumerSecret);
            var parts = NameValueParser.GetCollection(result, "&");

            this.Token       = parts["oauth_token"];
            this.TokenSecret = parts["oauth_token_secret"];

            // Save data in session for re-materialization
            SafeSession.Current["/Channels/LinkedIn/Redirect/Token"]       = Token;
            SafeSession.Current["/Channels/LinkedIn/Redirect/TokenSecret"] = TokenSecret;

            return(new Uri("https://api.linkedin.com/uas/oauth/authorize?oauth_token=" + Token + "&oauth_callback=" + BuildEnvironmentUrl()));
        }
        public void DecodeAuthorization()
        {
            var str =
                @"username=""Jonas"", realm=""localhost"", nonce=""836e689049bc4d7786d924c74fd03154"", uri=""/"", algorithm=MD5, response=""6585f223a56ddaafafff7f8db5aa77e0"", opaque=""b336fbc1c26c473580ec730851e71aa3"", qop=auth, nc=00000001, cnonce=""a9b3b4d9aa523026""";
            var parameters = new ParameterCollection();
            var parser = new NameValueParser();

            parser.Parse(str, parameters);

            Assert.Equal("Jonas", parameters["username"]);
            Assert.Equal("localhost", parameters["realm"]);
            Assert.Equal("836e689049bc4d7786d924c74fd03154", parameters["nonce"]);
            Assert.Equal("/", parameters["uri"]);
            Assert.Equal("MD5", parameters["algorithm"]);
            Assert.Equal("6585f223a56ddaafafff7f8db5aa77e0", parameters["response"]);
            Assert.Equal("b336fbc1c26c473580ec730851e71aa3", parameters["opaque"]);
            Assert.Equal("00000001", parameters["nc"]);
        }
        public void DecodeAuthorization()
        {
            var str =
                @"username=""ddssd"", realm=""DragonsDen"", nonce=""f09b846b702648ba871d82a6f908a6cc"", uri=""/"", algorithm=MD5, response=""d02b37c0e90773b21d3b8c8c448b1e9b"", qop=auth, nc=00000006, cnonce=""ad22c414546923eb""";
            var parameters = new ParameterCollection();
            var parser = new NameValueParser();

            parser.Parse(str, parameters);

            Assert.Equal("ddssd", parameters["username"]);
            Assert.Equal("DragonsDen", parameters["realm"]);
            Assert.Equal("f09b846b702648ba871d82a6f908a6cc", parameters["nonce"]);
            Assert.Equal("/", parameters["uri"]);
            Assert.Equal("MD5", parameters["algorithm"]);
            Assert.Equal("d02b37c0e90773b21d3b8c8c448b1e9b", parameters["response"]);
            Assert.Equal("auth", parameters["qop"]);
            Assert.Equal("00000006", parameters["nc"]);
            Assert.Equal("ad22c414546923eb", parameters["cnonce"]);
        }
Exemple #11
0
        public void DecodeAuthorization()
        {
            var str =
                @"username=""ddssd"", realm=""DragonsDen"", nonce=""f09b846b702648ba871d82a6f908a6cc"", uri=""/"", algorithm=MD5, response=""d02b37c0e90773b21d3b8c8c448b1e9b"", qop=auth, nc=00000006, cnonce=""ad22c414546923eb""";
            var parameters = new ParameterCollection();
            var parser     = new NameValueParser();

            parser.Parse(str, parameters);

            Assert.Equal("ddssd", parameters["username"]);
            Assert.Equal("DragonsDen", parameters["realm"]);
            Assert.Equal("f09b846b702648ba871d82a6f908a6cc", parameters["nonce"]);
            Assert.Equal("/", parameters["uri"]);
            Assert.Equal("MD5", parameters["algorithm"]);
            Assert.Equal("d02b37c0e90773b21d3b8c8c448b1e9b", parameters["response"]);
            Assert.Equal("auth", parameters["qop"]);
            Assert.Equal("00000006", parameters["nc"]);
            Assert.Equal("ad22c414546923eb", parameters["cnonce"]);
        }
        public static NewMessageDataHelper Parse(string mailtoString)
        {
            var uri = new Uri(mailtoString);

            var to      = new SourceAddress(String.Format("{0}@{1}", uri.UserInfo, uri.DnsSafeHost));
            var cc      = new SourceAddressCollection();
            var bcc     = new SourceAddressCollection();
            var subject = String.Empty;
            var body    = String.Empty;

            // See if there is a subject embedded in the url
            if (uri.Query.Length > 0)
            {
                var parts = NameValueParser.GetCollection(uri.Query, "?", "&");

                if (parts["subject"] != null)
                {
                    subject = parts["subject"];
                }

                if (parts["body"] != null)
                {
                    body = parts["body"];
                }

                if (parts["cc"] != null)
                {
                    cc = new SourceAddressCollection(parts["cc"]);
                }

                if (parts["bcc"] != null)
                {
                    bcc = new SourceAddressCollection(parts["bcc"]);
                }
            }

            return(new NewMessageDataHelper {
                Context = subject, To = to.ToList(), Cc = cc, Bcc = bcc, Body = body
            });
        }
Exemple #13
0
 public void TestParser()
 {
     var pd      = new NameValueParser("OfferID=6;Instrument=AUD/USD;Bid=1.03305;Ask=1.03335;Hi=1.03749;Low=1.02871;IntrS=-1.72;IntrB=0.81;ContractCurrency=AUD;ContractSize=1;Digits=5;DefaultSortOrder=6;PipCost=1;MMR=200;Time=2011-04-05 19:55:58;BidChangeDirection=0;AskChangeDirection=1;HiChangeDirection=0;LowChangeDirection=-1;QuoteID=FXCM-AUDUSD-2623346;BidID=;AskID=;BidExpireDate=;AskExpireDate=;BidTradable=T;AskTradable=T;PointSize=0.0001;InstrumentType=1;");
     var offerId = pd.GetInt("OfferID");
 }
        public IAuthenticationUser Authenticate(IRequest request)
        {
            var authHeader = request.Headers["Authorization"];
            if (authHeader == null)
                return null;


            var parser = new NameValueParser();
            var parameters = new ParameterCollection();
            parser.Parse(authHeader.Value.Remove(0, AuthenticationScheme.Length + 1), parameters);

            var nc = int.Parse(parameters["nc"], NumberStyles.AllowHexSpecifier);
            if (!_nonceService.IsValid(parameters["nonce"], nc) && !DisableNonceCheck)
                throw new HttpException(HttpStatusCode.Forbidden, "Invalid nonce/nc.");

            // request authentication information
            var username = parameters["username"];
            var user = _userService.Lookup(username, request.Uri);
            if (user == null)
                return null;

            var uri = parameters["uri"];
            // Encode authentication info
            var ha1 = string.IsNullOrEmpty(user.HA1)
                          ? GetHa1(_realmRepository.GetRealm(request), username, user.Password)
                          : user.HA1;

            // encode challenge info
            var a2 = String.Format("{0}:{1}", request.Method, uri);
            var ha2 = GetMd5HashBinHex(a2);
            var hashedDigest = Encrypt(ha1, ha2, parameters["qop"],
                                       parameters["nonce"], parameters["nc"], parameters["cnonce"]);

            //validate
            if (parameters["response"] == hashedDigest)
            {
                return user;
            }

            return null;
        }
Exemple #15
0
 public string ParseVerifier(string returnValue)
 {
     return(NameValueParser.GetCollection(new Uri(returnValue).Query, "&")["oauth_verifier"]);
 }
Exemple #16
0
        public static string Post(string url, string data, List <UploadFile> files, bool throwOnError)
        {
            try
            {
                var uri     = new Uri(url);
                var request = (HttpWebRequest)WebRequest.Create(
                    String.Format("{0}://{1}:{2}{3}", uri.Scheme, uri.Host, uri.Port, uri.AbsolutePath));

                AttachCertificate(request);

                using (var response = HttpUploadHelper.Upload(request, files.ToArray(), NameValueParser.GetCollection(data, "&")))
                    using (var result = response.GetResponseStream())
                        return(result.ReadString());
            }
            catch (Exception ex)
            {
                string message = String.Empty;

                if (ex is WebException)
                {
                    var wex      = (WebException)ex;
                    var response = (HttpWebResponse)wex.Response;

                    if (response != null)
                    {
                        using (var stream = response.GetResponseStream())
                            message = stream.ReadString();
                    }
                }

                Logger.Error("An error has occured while calling url. Url = {0}, Data = {1}, Exception = {2}, Message = {3}", LogSource.ServiceCall, url, data, ex, message);

                if (throwOnError)
                {
                    throw;
                }

                return(null);
            }
        }
        public IEnumerable <FbStatus> GetStatusses(int pageSize)
        {
            Authenticate();

            string call_id = GetNextCallNr();
            string limit   = pageSize.ToString();

            Dictionary <string, string> requestParams = new Dictionary <string, string>();

            requestParams.Add("method", "stream.get");
            requestParams.Add("api_key", apiKey);
            requestParams.Add("session_key", sessionKey);
            requestParams.Add("call_id", call_id);
            requestParams.Add("source_ids", "");
            requestParams.Add("v", "1.0");
            requestParams.Add("limit", limit);

            var result = channel.GetStream(apiKey, sessionKey, call_id, GenerateSignature(requestParams, sessionSecret), "", limit);

            XNamespace ns = result.GetDefaultNamespace();

            foreach (XElement element in result.Descendants(ns + "stream_post"))
            {
                var status = new FbStatus();

                try
                {
                    var id          = element.Element(ns + "actor_id").Value;
                    var userElement = result.Descendants(ns + "profile").First(p => p.Element(ns + "id").Value == id);

                    status.From = new SourceAddress(id, userElement.Element(ns + "name").Value,
                                                    userElement.Element(ns + "pic_square").Value);

                    if (element.Element(ns + "target_id") != null && !String.IsNullOrEmpty(element.Element(ns + "target_id").Value))
                    {
                        var toid = element.Element(ns + "target_id").Value;

                        if (!String.IsNullOrEmpty(toid))
                        {
                            var toUserElement = result.Descendants(ns + "profile").First(p => p.Element(ns + "id").Value == toid);

                            status.To = new SourceAddress(toid, toUserElement.Element(ns + "name").Value,
                                                          toUserElement.Element(ns + "pic_square").Value);
                        }
                    }

                    status.Uid         = Int64.Parse(element.Element(ns + "actor_id").Value);
                    status.StatusId    = element.Element(ns + "post_id").Value;
                    status.Message     = element.Element(ns + "message").Value;
                    status.DateCreated = Int64.Parse(element.Element(ns + "created_time").Value).ToUnixTime();

                    foreach (var commentElement in element.Descendants(ns + "comment"))
                    {
                        var comment            = new FbStatus();
                        var commentid          = commentElement.Element(ns + "fromid").Value;
                        var commentUserElement = result.Descendants(ns + "profile").First(p => p.Element(ns + "id").Value == commentid);

                        comment.From = new SourceAddress(commentid, commentUserElement.Element(ns + "name").Value,
                                                         commentUserElement.Element(ns + "pic_square").Value);

                        comment.Uid         = Int64.Parse(commentElement.Element(ns + "fromid").Value);
                        comment.StatusId    = commentElement.Element(ns + "id").Value;
                        comment.Message     = commentElement.Element(ns + "text").Value;
                        comment.DateCreated = Int64.Parse(commentElement.Element(ns + "time").Value).ToUnixTime();

                        status.Comments.Add(comment);
                    }

                    foreach (var attachmentElement in element.Descendants(ns + "stream_media"))
                    {
                        var attachment = new FbAttachment();
                        attachment.MediaType = (FbMediaType)Enum.Parse(typeof(FbMediaType), attachmentElement.Element(ns + "type").Value, true);

                        switch (attachment.MediaType)
                        {
                        case FbMediaType.Link:
                        {
                            attachment.TargetUrl       = HttpUtility.HtmlDecode(attachmentElement.Element(ns + "href").Value);
                            attachment.PreviewAltText  = HttpUtility.HtmlDecode(attachmentElement.Element(ns + "alt").Value);
                            attachment.PreviewImageUrl = HttpUtility.HtmlDecode(attachmentElement.Element(ns + "src").Value);

                            break;
                        }

                        case FbMediaType.Photo:
                        {
                            attachment.TargetUrl       = HttpUtility.HtmlDecode(attachmentElement.Element(ns + "href").Value);
                            attachment.PreviewAltText  = HttpUtility.HtmlDecode(attachmentElement.Element(ns + "alt").Value);
                            attachment.PreviewImageUrl = HttpUtility.HtmlDecode(attachmentElement.Element(ns + "src").Value);

                            break;
                        }

                        case FbMediaType.Video:
                        {
                            var src       = new Uri(attachmentElement.Element(ns + "src").Value);
                            var uriParams = NameValueParser.GetCollection(src.Query, "&");

                            attachment.TargetUrl       = HttpUtility.HtmlDecode(attachmentElement.Element(ns + "video").Element(ns + "display_url").Value);
                            attachment.PreviewAltText  = HttpUtility.HtmlDecode(attachmentElement.Element(ns + "alt").Value);
                            attachment.PreviewImageUrl = HttpUtility.UrlDecode(uriParams["url"]);

                            break;
                        }
                        }

                        status.Attachments.Add(attachment);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error("Unable to retreive user source address. Result = {0}. Exception = {1}", LogSource.Channel, element.Value, ex);

                    continue;
                }

                yield return(status);
            }
        }
        public IAuthenticationUser Authenticate(IRequest request)
        {
            var authHeader = request.Headers["Authorization"];
            if (authHeader == null)
                return null;


            if (_timer == null)
            {
                lock (Nonces)
                {
                    if (_timer == null)
                        _timer = new Timer(ManageNonces, null, 15000, 15000);
                }
            }

            var parser = new NameValueParser();
            var parameters = new ParameterCollection();
            parser.Parse(authHeader.Value.Remove(0, AuthenticationScheme.Length + 1), parameters);
            if (!IsValidNonce(parameters["nonce"]) && !DisableNonceCheck)
                throw new HttpException(HttpStatusCode.Unauthorized, "Invalid nonce.");

            // request authentication information
            var username = parameters["username"];
            var user = _userService.Lookup(username, request.Uri);
            if (user == null)
                return null;

            // Encode authentication info
            var ha1 = string.IsNullOrEmpty(user.HA1) ? GetHa1(_realmRepository.GetRealm(request), username, user.Password) : user.HA1;

            // encode challenge info
            var a2 = String.Format("{0}:{1}", request.Method, request.Uri.AbsolutePath);
            var ha2 = GetMd5HashBinHex(a2);
            var hashedDigest = Encrypt(ha1, ha2, parameters["qop"],
                                       parameters["nonce"], parameters["nc"], parameters["cnonce"]);

            //validate
            if (parameters["response"] == hashedDigest)
            {
                return user;
            }

            return null;
        }