コード例 #1
0
        //////////////////////////////////////////////////////////////////////

        /// <summary>Retrieves information about the AuthSub token.
        /// If the <code>key</code> is non-null, the token will be used securely
        /// and the request to revoke the token will be signed.
        /// </summary>
        /// <param name="protocol">the protocol to use to communicate with the server</param>
        /// <param name="domain">the domain at which the authentication server exists</param>
        /// <param name="token">tthe AuthSub token for which to receive information </param>
        /// <param name="key">the private key to sign the request</param>
        /// <returns>the token information in the form of a Dictionary from the name of the
        ///  attribute to the value of the attribute</returns>
        //////////////////////////////////////////////////////////////////////
        public static Dictionary <String, String> GetTokenInfo(
            String protocol,
            String domain,
            String token,
            AsymmetricAlgorithm key)
        {
            HttpWebResponse response;

            try
            {
                string tokenInfoUrl = GetTokenInfoUrl(protocol, domain);
                Uri    uri          = new Uri(tokenInfoUrl);

                HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;

                string header = formAuthorizationHeader(token, key, uri, "GET");
                request.Headers.Add(header);

                response = request.GetResponse() as HttpWebResponse;
            }
            catch (WebException e)
            {
                Tracing.TraceMsg("GetTokenInfo failed " + e.Status);
                throw new GDataRequestException("Execution of GetTokenInfo", e);
            }

            if (response != null)
            {
                int code = (int)response.StatusCode;
                if (code != 200)
                {
                    throw new GDataRequestException("Execution of revokeToken request returned unexpected result: " + code, response);
                }

                TokenCollection tokens = Utilities.ParseStreamInTokenCollection(response.GetResponseStream());
                if (tokens != null)
                {
                    return(tokens.CreateDictionary());
                }
            }

            return(null);
        }
コード例 #2
0
        /// <summary>
        /// this will take one category part and parse it
        /// </summary>
        /// <param name="category"></param>
        /// <returns></returns>
        private void ParseCategoryString(string category)
        {
            // take the string, and create some category objects out of it...

            // replace the curly braces and the or operator | so that we can tokenize better
            category = category.Replace("%7B", "{");
            category = category.Replace("%7D", "}");
            category = category.Replace("%7C", "|");
            category = Utilities.UrlDecodedValue(category);

            // let's see if it's the only one...
            TokenCollection tokens = new TokenCollection(category, new char[1] {
                '|'
            });
            QueryCategoryOperator op = QueryCategoryOperator.AND;

            foreach (String token in tokens)
            {
                // each one is a category
                QueryCategory cat = new QueryCategory(token, op);
                Categories.Add(cat);
                op = QueryCategoryOperator.OR;
            }
        }
コード例 #3
0
        /// <summary>protected void ParseUri</summary>
        /// <param name="targetUri">takes an incoming Uri string and parses all the properties out of it</param>
        /// <returns>throws a query exception when it finds something wrong with the input, otherwise returns a baseuri</returns>
        protected virtual Uri ParseUri(Uri targetUri)
        {
            Reset();
            StringBuilder newPath = null;
            UriBuilder    newUri  = null;

            if (targetUri != null)
            {
                TokenCollection tokens;
                // want to check some basic things on this guy first...
                ValidateUri(targetUri);
                newPath      = new StringBuilder("", 2048);
                newUri       = new UriBuilder(targetUri);
                newUri.Path  = null;
                newUri.Query = null;

                // now parse the query string and take the properties out
                string[] parts     = targetUri.Segments;
                bool     fCategory = false;

                foreach (string part in parts)
                {
                    string segment = CleanPart(part);
                    if (segment.Equals("-"))
                    {
                        // found the category simulator
                        fCategory = true;
                    }
                    else if (fCategory)
                    {
                        ParseCategoryString(segment);
                    }
                    else
                    {
                        newPath.Append(part);
                    }
                }

                char[] deli = { '?', '&' };

                string source = HttpUtility.UrlDecode(targetUri.Query);
                tokens = new TokenCollection(source, deli);
                foreach (String token in tokens)
                {
                    if (token.Length > 0)
                    {
                        char[]   otherDeli  = { '=' };
                        String[] parameters = token.Split(otherDeli, 2);
                        switch (parameters[0])
                        {
                        case "q":
                            Query = parameters[1];
                            break;

                        case "author":
                            Author = parameters[1];
                            break;

                        case "start-index":
                            StartIndex = int.Parse(parameters[1], CultureInfo.InvariantCulture);
                            break;

                        case "max-results":
                            NumberToRetrieve = int.Parse(parameters[1], CultureInfo.InvariantCulture);
                            break;

                        case "updated-min":
                            StartDate = DateTime.Parse(parameters[1], CultureInfo.InvariantCulture);
                            break;

                        case "updated-max":
                            EndDate = DateTime.Parse(parameters[1], CultureInfo.InvariantCulture);
                            break;

                        case "published-min":
                            MinPublication = DateTime.Parse(parameters[1], CultureInfo.InvariantCulture);
                            break;

                        case "published-max":
                            MaxPublication = DateTime.Parse(parameters[1], CultureInfo.InvariantCulture);
                            break;

                        case "category":
                            ParseCategoryQueryString(parameters[1]);
                            break;

                        case "xoauth_requestor_id":
                            OAuthRequestorId = parameters[1];
                            break;

                        default:
                            break;
                        }
                    }
                }
            }

            if (newPath != null)
            {
                if (newPath[newPath.Length - 1] == '/')
                {
                    newPath.Length = newPath.Length - 1;
                }

                newUri.Path = newPath.ToString();
                baseUri     = newUri.Uri.AbsoluteUri;
                UseSSL      = baseUri.StartsWith("https://");
            }

            return(null);
        }
コード例 #4
0
        /// <summary>goes to the Google auth service, and gets a new auth token</summary>
        /// <returns>the auth token, or NULL if none received</returns>
        public static string QueryClientLoginToken(
            GDataCredentials gc,
            string serviceName,
            string applicationName,
            bool fUseKeepAlive,
            IWebProxy proxyServer,
            Uri clientLoginHandler)
        {
            Tracing.Assert(gc != null, "Do not call QueryAuthToken with no network credentials");
            if (gc == null)
            {
                throw new System.ArgumentNullException("nc", "No credentials supplied");
            }

            HttpWebRequest authRequest = WebRequest.Create(clientLoginHandler) as HttpWebRequest;

            authRequest.KeepAlive = fUseKeepAlive;

            if (proxyServer != null)
            {
                authRequest.Proxy = proxyServer;
            }

            string accountType = GoogleAuthentication.AccountType;

            if (!String.IsNullOrEmpty(gc.AccountType))
            {
                accountType += gc.AccountType;
            }
            else
            {
                accountType += GoogleAuthentication.AccountTypeDefault;
            }

            WebResponse     authResponse = null;
            HttpWebResponse response     = null;

            string authToken = null;

            try
            {
                authRequest.ContentType = HttpFormPost.Encoding;
                authRequest.Method      = HttpMethods.Post;
                ASCIIEncoding encoder = new ASCIIEncoding();

                string user = gc.Username == null ? "" : gc.Username;
                string pwd  = gc.getPassword() == null ? "" : gc.getPassword();

                // now enter the data in the stream
                string postData = GoogleAuthentication.Email + "=" + Utilities.UriEncodeUnsafe(user) + "&";
                postData += GoogleAuthentication.Password + "=" + Utilities.UriEncodeUnsafe(pwd) + "&";
                postData += GoogleAuthentication.Source + "=" + Utilities.UriEncodeUnsafe(applicationName) + "&";
                postData += GoogleAuthentication.Service + "=" + Utilities.UriEncodeUnsafe(serviceName) + "&";
                if (gc.CaptchaAnswer != null)
                {
                    postData += GoogleAuthentication.CaptchaAnswer + "=" + Utilities.UriEncodeUnsafe(gc.CaptchaAnswer) + "&";
                }

                if (gc.CaptchaToken != null)
                {
                    postData += GoogleAuthentication.CaptchaToken + "=" + Utilities.UriEncodeUnsafe(gc.CaptchaToken) + "&";
                }

                postData += accountType;

                byte[] encodedData = encoder.GetBytes(postData);
                authRequest.ContentLength = encodedData.Length;

                Stream requestStream = authRequest.GetRequestStream();
                requestStream.Write(encodedData, 0, encodedData.Length);
                requestStream.Close();
                authResponse = authRequest.GetResponse();
                response     = authResponse as HttpWebResponse;
            }
            catch (WebException e)
            {
                response = e.Response as HttpWebResponse;
                if (response == null)
                {
                    Tracing.TraceMsg("QueryAuthtoken failed " + e.Status + " " + e.Message);
                    throw;
                }
            }

            if (response != null)
            {
                // check the content type, it must be text
                if (!response.ContentType.StartsWith(HttpFormPost.ReturnContentType))
                {
                    throw new GDataRequestException("Execution of authentication request returned unexpected content type: " + response.ContentType, response);
                }

                TokenCollection tokens = Utilities.ParseStreamInTokenCollection(response.GetResponseStream());
                authToken = Utilities.FindToken(tokens, GoogleAuthentication.AuthToken);

                if (authToken == null)
                {
                    throw Utilities.getAuthException(tokens, response);
                }

                // failsafe. if getAuthException did not catch an error...
                int code = (int)response.StatusCode;
                if (code != 200)
                {
                    throw new GDataRequestException("Execution of authentication request returned unexpected result: " + code, response);
                }
            }

            Tracing.Assert(authToken != null, "did not find an auth token in QueryAuthToken");
            if (authResponse != null)
            {
                authResponse.Close();
            }

            return(authToken);
        }
コード例 #5
0
        /// <summary>parses a form response stream in token form for a specific value
        /// </summary>
        /// <param name="inputStream">the stream to read and parse</param>
        /// <param name="key">the key to search for</param>
        /// <returns> the string in the tokenized stream </returns>
        public static string ParseValueFormStream(Stream inputStream, string key)
        {
            TokenCollection tokens = ParseStreamInTokenCollection(inputStream);

            return(FindToken(tokens, key));
        }
コード例 #6
0
 /// <summary>Standard constructor</summary>
 public TokenEnumerator(TokenCollection tokens)
 {
     _tokens = tokens;
 }