Ejemplo n.º 1
0
        public void QueryStringMultipleTest()
        {
            string str = "http://mysite.com/page1?id=3123&format=json&format=xml";

            var query = new UrlEncodingParser(str);

            Assert.IsTrue(query["id"] == "3123");
            Assert.IsTrue(query["format"] == "json,xml", "wrong format " + query["format"]);

            // multiple format strings
            string[] formats = query.GetValues("format");
            Assert.IsTrue(formats.Length == 2);

            query.SetValues("multiple", new[]
            {
                "1",
                "2",
                "3"
            });

            var url = query.ToString();

            Console.WriteLine(url);

            Assert.IsTrue(url ==
                          "http://mysite.com/page1?id=3123&format=json&format=xml&multiple=1&multiple=2&multiple=3");
        }
Ejemplo n.º 2
0
        public void QueryStringTest()
        {
            string str = "http://mysite.com/page1?id=3123&format=json&action=edit&text=It's%20a%20brave%20new%20world!";

            var query = new UrlEncodingParser(str);

            Console.WriteLine(query);

            Assert.IsTrue(query["id"] == "3123");
            Assert.IsTrue(query["format"] == "json", "wrong format " + query["format"]);
            Assert.IsTrue(query["action"] == "edit");

            Console.WriteLine(query["text"]);
            // It's a brave new world!

            query["id"]     = "4123";
            query["format"] = "xml";
            query["name"]   = "<< It's a brave new world! say what?";

            var url = query.ToString();

            Console.WriteLine(url);
            Console.Write(query.ToString());
            //http://mysite.com/page1?id=4123&format=xml&action=edit&
            //text=It's%20a%20brave%20new%20world!&name=%3C%3C%20It's%20a%20brave%20new%20world!
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Generates a signature using the specified signatureType
        /// </summary>
        /// <param name="httpMethod">The http method used</param>
        /// <param name="url">The full url to be signed</param>
        /// <param name="parametersIn">The collection of parameters to sign</param>
        /// <param name="consumerSecret">The OAuth consumer secret used to generate the signature</param>
        /// <returns>A base64 string of the hash value</returns>
        private static string GenerateSignature(string httpMethod, Uri url, NameValueCollection parametersIn, string consumerSecret)
        {
            // Work with a copy of the parameters so the caller's data is not changed
            var parameters = new NameValueCollection(parametersIn);

            // https://tools.ietf.org/html/rfc5849#section-3.4.1.3.1
            // The query component is parsed into a list of name/value pairs by treating it as an
            // "application/x-www-form-urlencoded" string, separating the names and values and
            // decoding them as defined by [W3C.REC - html40 - 19980424], Section 17.13.4.
            //
            // Unescape the query so that it is not doubly escaped by UrlEncodingParser.
            var querystring = new UrlEncodingParser(Uri.UnescapeDataString(url.Query));

            parameters.Add(querystring);

            var signatureBase = GenerateSignatureBase(httpMethod, url, parameters);

            // Note that in LTI, the TokenSecret (second part of the key) is blank
            var hmacsha1 = new HMACSHA1
            {
                Key = Encoding.ASCII.GetBytes($"{consumerSecret.ToRfc3986EncodedString()}&")
            };

            var dataBuffer = Encoding.ASCII.GetBytes(signatureBase);
            var hashBytes  = hmacsha1.ComputeHash(dataBuffer);

            return(Convert.ToBase64String(hashBytes));
        }
Ejemplo n.º 4
0
        public void QueryStringPlusSigns()
        {
            string str = "http://mysite.com/page1?text=It's+a+depressing+world+out+there";

            var query = new UrlEncodingParser(str, true);

            string text = query["text"];

            Console.WriteLine(text);

            Assert.IsFalse(text.Contains("+"));
            Assert.IsTrue(text.Contains(" "));;
        }
Ejemplo n.º 5
0
    private void Awake()
    {
        Instance = this;
        var    query = new UrlEncodingParser(Application.absoluteURL);
        string token = query.Get("token");

        if (!string.IsNullOrEmpty(token))
        {
            StartCoroutine(Connect(token));
        }
        else
        {
            ShowError("Invalid token.");
        }
    }
Ejemplo n.º 6
0
        internal string ReplaceQueryStringValuePairs(string url, string replaceKeys)
        {
            if (string.IsNullOrEmpty(replaceKeys))
            {
                return(url);
            }

            var urlQuery     = new UrlEncodingParser(url);
            var replaceQuery = new UrlEncodingParser(replaceKeys);

            foreach (string key in replaceQuery.Keys)
            {
                urlQuery[key] = replaceQuery[key];
            }

            return(urlQuery.ToString());
        }
Ejemplo n.º 7
0
        private LinkActivation CreateLinkActivation(string s)
        {
            var query = string.Empty;
            var args  = new Dictionary <string, string>();

            try
            {
                var parser = new UrlEncodingParser(s);
                args  = parser;
                query = parser.Query;
            }
            catch (Exception)
            {
            }

            return(new LinkActivation(s, query, args));
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Calculate the OAuth Signature for this request using custom parameters.
        /// </summary>
        /// <param name="parameters">The set of parameters to be included in the signature.</param>
        /// <param name="consumerSecret">The OAuth Consumer Secret to use.</param>
        /// <returns>The calculated OAuth Signature.</returns>
        /// <remarks>
        /// This is typically used by Tool Consumers that perform custom parameter substitution prior
        /// to signing the request.
        /// </remarks>
        public string GenerateSignature(NameValueCollection parameters, string consumerSecret)
        {
            // The LTI spec says to include the querystring parameters
            // when calculating the signature base string. Unescape the
            // query so that it is not doubly escaped by UrlEncodingParser.
            var querystring = new UrlEncodingParser(Uri.UnescapeDataString(Url.Query));

            parameters.Add(querystring);

            var signature = OAuthUtility.GenerateSignature(HttpMethod, Url, parameters, consumerSecret);

            // Now remove the querystring parameters so they are not sent twice
            // (once in the action URL and once in the form data)
            foreach (var key in querystring.AllKeys)
            {
                parameters.Remove(key);
            }

            return(signature);
        }
    public static string FixUrl(string url)
    {
        url = url.Trim();

        if (IsBase64String(url))
        {
            byte[] data = Convert.FromBase64String(url);
            url = Encoding.UTF8.GetString(data);
        }

        if (!url.Contains("http:") && !url.Contains("https:") && !url.Contains("ftp:") && !url.Contains("ftps:"))
        {
            url = $"http://{url}";
        }

        Uri uri = new Uri(url);

        if (!url.EndsWith("/") && string.IsNullOrWhiteSpace(Path.GetFileName(WebUtility.UrlDecode(uri.AbsolutePath))) && string.IsNullOrWhiteSpace(uri.Query))
        {
            url += "/";
        }

        if (uri.Host == Constants.GoogleDriveDomain)
        {
            UrlEncodingParser urlEncodingParser = new UrlEncodingParser(url);

            if (urlEncodingParser.AllKeys.Contains("usp"))
            {
                urlEncodingParser.Remove("usp");
            }

            url = urlEncodingParser.ToString();
        }

        return(url);
    }
        public string RetrieveSAMLAssertion(Uri identityProvider)
        {
            string result = null;

            //ImpersonationState impersonationState = null;
            try
            {
                CookieContainer cookies = new CookieContainer();
                //if (credentials != null)
                //{
                //    impersonationState = ImpersonationState.Impersonate(credentials.GetCredential(identityProvider, authenticationType));
                //}
                using (HttpWebResponse httpWebResponse = this.QueryProvider(identityProvider, cookies, null))
                {
                    using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
                        result = streamReader.ReadToEnd();
                    LoggerInternal(Lang.DebugIdpResponded, LogType.Debug);
                    Dictionary <string, string> values = new Dictionary <string, string>();
                    if (Credentials != null)
                    {
                        values.Add("USERNAME", Credentials.UserName);
                        values.Add("PASSWORD", Credentials.Password);
                    }
                    var formResponse = GetFormData(result, values);

                    bool stopRequest = false;
                    int  tryCount    = 1;
                    do
                    {
                        Uri postTo = new Uri(httpWebResponse.ResponseUri, formResponse.Action);
                        using (HttpWebResponse httpWebResponsePost = this.PostProvider(postTo, cookies, httpWebResponse.ResponseUri, formResponse.FormData))
                        {
                            if (httpWebResponsePost.StatusCode == HttpStatusCode.Found)
                            {
                                string location = httpWebResponsePost.Headers[HttpResponseHeader.Location];
                                if (!string.IsNullOrWhiteSpace(location))
                                {
                                    Uri uLocation = new Uri(location);
                                    var qry       = new UrlEncodingParser(uLocation);
                                    if (qry.AllKeys.Contains("TAM_OP", StringComparer.CurrentCultureIgnoreCase))
                                    {
                                        string TAM_OP = qry["TAM_OP"];
                                        //https://www.ibm.com/support/knowledgecenter/en/SSPREK_9.0.0/com.ibm.isam.doc/wrp_config/concept/con_op_redir.html
                                        switch (TAM_OP.ToUpperInvariant())
                                        {
                                        case "ACCT_INACTIVATED":
                                            throw new IbmIamException(Lang.Error_ACCT_INACTIVATED);

                                        case "ACCT_LOCKED":
                                            throw new IbmIamException(Lang.Error_ACCT_LOCKED);

                                        case "CERT_LOGIN":
                                            throw new IbmIamException(Lang.Error_CERT_LOGIN);

                                        case "CERT_STEPUP_HTTP":
                                            throw new IbmIamException(Lang.Error_CERT_STEPUP_HTTP);

                                        case "EAI_AUTH_ERROR":
                                            throw new IbmIamException(Lang.Error_EAI_AUTH_ERROR);

                                        case "ERROR":
                                        {
                                            string ERROR_CODE = qry["ERROR_CODE"];
                                            switch (ERROR_CODE.ToUpperInvariant())
                                            {
                                            case "0XPWDEXPRD":
                                                string url = qry["URL"];
                                                throw new IbmIamPasswordExpiredException(Lang.Error_0XPWDEXPRD)
                                                      {
                                                          HelpLink = url
                                                      };

                                            default:
                                                throw new IbmIamErrorException(string.Format(CultureInfo.CurrentCulture, Lang.Error_Unknown_Error_Code, ERROR_CODE), ERROR_CODE);
                                            }
                                        }

                                        case "FAILED_CERT":
                                            throw new IbmIamException(Lang.Error_FAILED_CERT);

                                        case "HELP":
                                            throw new IbmIamException(Lang.Error_HELP);

                                        case "LOGIN":
                                            throw new IbmIamException(Lang.Error_LOGIN);

                                        case "LOGIN_SUCCESS":
                                            throw new IbmIamException(Lang.Error_LOGIN_SUCCESS);

                                        case "LOGOUT":
                                            throw new IbmIamException(Lang.Error_LOGOUT);

                                        case "PASSWD":
                                            throw new IbmIamException(Lang.Error_PASSWD);

                                        case "PASSWD_EXP":
                                        {
                                            string url = qry["URL"];
                                            throw new IbmIamPasswordExpiredException(Lang.Error_PASSWD_EXP)
                                                  {
                                                      HelpLink = url
                                                  };
                                        }

                                        case "PASSWD_REP_FAILURE":
                                            throw new IbmIamException(Lang.Error_PASSWD_REP_FAILURE);

                                        case "PASSWD_REP_SUCCESS":
                                            throw new IbmIamException(Lang.Error_PASSWD_REP_SUCCESS);

                                        case "PASSWD_WARN":
                                            throw new IbmIamException(Lang.Error_PASSWD_WARN);

                                        case "PASSWD_WARN_FAILURE":
                                            throw new IbmIamException(Lang.Error_PASSWD_WARN_FAILURE);

                                        case "STEPUP":
                                            throw new IbmIamException(Lang.Error_STEPUP);

                                        case "SWITCH_USER":
                                            throw new IbmIamException(Lang.Error_SWITCH_USER);

                                        case "TOO_MANY_SESSIONS":
                                            throw new IbmIamException(Lang.Error_TOO_MANY_SESSIONS);

                                        default:
                                            throw new IbmIamException(string.Format(CultureInfo.CurrentCulture, Lang.Error_Unknown_Operation_Response, TAM_OP));
                                        }
                                    }
                                    else
                                    {
                                        using (HttpWebResponse httpRedirectResponse = this.QueryProvider(uLocation, cookies, httpWebResponse.ResponseUri, true))
                                        {
                                            using (StreamReader streamReader = new StreamReader(httpRedirectResponse.GetResponseStream()))
                                            {
                                                result = streamReader.ReadToEnd();
                                                if (!SAMLResponseField.IsMatch(result))
                                                {
                                                    // This should be asking for the MFA now
                                                    formResponse = GetFormData(result, values);
                                                }
                                                else
                                                {
                                                    stopRequest = true;
                                                    MatchCollection resposne = SAMLResponseField.Matches(result);
                                                    foreach (Match data in resposne)
                                                    {
                                                        return(Assertion = data.Groups[1].Value);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                using (StreamReader streamReader = new StreamReader(httpWebResponsePost.GetResponseStream()))
                                {
                                    result = streamReader.ReadToEnd();
                                    string errMsg = CheckErrorMessage(result);
                                    if (!string.IsNullOrWhiteSpace(errMsg))
                                    {
                                        throw new IbmIamException(errMsg);
                                    }
                                    else if (!SAMLResponseField.IsMatch(result))
                                    {
                                        // This should be asking for the MFA now
                                        formResponse = GetFormData(result, values);
                                    }
                                    else
                                    {
                                        stopRequest = true;
                                        MatchCollection resposne = SAMLResponseField.Matches(result);
                                        foreach (Match data in resposne)
                                        {
                                            return(Assertion = data.Groups[1].Value);
                                        }
                                    }
                                }
                            }
                        }
                        tryCount++;
                    }while (!stopRequest && tryCount < 5);
                }
            }
            finally
            {
                //if (impersonationState != null)
                //{
                //    impersonationState.Dispose();
                //}
            }
            throw new Exception(Lang.ErrorInvalidCredentials);
        }
Ejemplo n.º 11
0
        public void WriteUrlTest()
        {
            // URL only
            string url = "http://test.com/page";

            var query = new UrlEncodingParser(url);

            query["id"]   = "321312";
            query["name"] = "rick";

            url = query.ToString();
            Console.WriteLine(url);

            Assert.IsTrue(url.Contains("name="));
            Assert.IsTrue(url.Contains("http://"));

            // URL with ? but no query
            url = "http://test.com/page?";

            query         = new UrlEncodingParser(url);
            query["id"]   = "321312";
            query["name"] = "rick";

            url = query.ToString();
            Console.WriteLine(url);

            Assert.IsTrue(url.Contains("name="));


            // URL with query
            url = "http://test.com/page?q=search";

            query         = new UrlEncodingParser(url);
            query["id"]   = "321312";
            query["name"] = "rick";

            url = query.ToString();
            Console.WriteLine(url);

            Assert.IsTrue(url.Contains("name="));
            Assert.IsTrue(url.Contains("http://"));


            // Raw query data
            url = "q=search&name=james";

            query         = new UrlEncodingParser(url);
            query["id"]   = "321312";
            query["name"] = "rick";

            url = query.ToString();
            Console.WriteLine(url);

            Assert.IsTrue(url.Contains("name="));
            Assert.IsTrue(!url.Contains("http://"));


            // No data at all
            url = null;

            query         = new UrlEncodingParser();
            query["id"]   = "321312";
            query["name"] = "rick";

            url = query.ToString();
            Console.WriteLine(url);

            Assert.IsTrue(url.Contains("name="));
            Assert.IsTrue(!url.Contains("http://"));
        }