ParseQueryString() public static method

public static ParseQueryString ( Uri uri ) : string>.IReadOnlyDictionary
uri Uri
return string>.IReadOnlyDictionary
示例#1
0
        /// <summary>
        /// Get the auth code for the user. Used to get the tokens used for future requests.
        /// </summary>
        /// <param name="NPSSO">The NPSSO id for the user.</param>
        /// <returns>A results object containing the type 'CodeResult'</returns>
        public async Task <Result> GetAuthCodeAsync(string NPSSO)
        {
            var baseAddress     = new Uri("https://auth.api.sonyentertainmentnetwork.com");
            var cookieContainer = new CookieContainer();

            cookieContainer.Add(baseAddress, new Cookie("npsso", NPSSO));
            using (var handler = new HttpClientHandler()
            {
                CookieContainer = cookieContainer, AllowAutoRedirect = false
            })
                using (var client = new HttpClient(handler)
                {
                    BaseAddress = baseAddress
                })
                {
                    var response = await client.GetAsync(EndPoints.CodeAuth);

                    var codeUrl     = response.Headers.Location.OriginalString;
                    var queryString = UriExtensions.ParseQueryString(codeUrl.ToString());
                    if (queryString.ContainsKey("authentication_error"))
                    {
                        return(ErrorHandler.CreateErrorObject(new Result(), "Failed to get OAuth Code (Authentication_error)", "Auth"));
                    }

                    if (!queryString.ContainsKey("code"))
                    {
                        return(ErrorHandler.CreateErrorObject(new Result(), "Failed to get OAuth Code (No code)", "Auth"));
                    }

                    return(new Result()
                    {
                        IsSuccess = true, ResultJson = "{\"code\": \"" + queryString["code"] + "\"}"
                    });
                }
        }
示例#2
0
        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            _vm = (LoginPageViewModel)DataContext;
            var             args = e.NavigationParameter as ProtocolActivatedEventArgs;
            string          jsonObjectString;
            LoginUserEntity user;

            if (args != null)
            {
                IReadOnlyDictionary <string, string> queryString = UriExtensions.ParseQueryString(args.Uri);
                user = await _vm.NewLogIn(queryString["sessionId"]);

                jsonObjectString = JsonConvert.SerializeObject(user);
                Frame.Navigate(typeof(MainPage), jsonObjectString);
                return;
            }
            user = await _vm.IsLoggedIn();

            if (user == null)
            {
                return;
            }
            jsonObjectString = JsonConvert.SerializeObject(user);
            Frame.Navigate(typeof(MainPage), jsonObjectString);
        }
示例#3
0
        public static BitmapImage CreateSizedBitmap(FrameworkElement container, Uri uri, bool backgroundCreation = true)
        {
            Dictionary <string, string> queryString = UriExtensions.ParseQueryString(uri);
            double result1 = 0.0;
            double result2 = 0.0;

            if (queryString.ContainsKey("wh"))
            {
                string[] strArray = queryString["wh"].Split((char[])new char[1] {
                    '_'
                });
                if (strArray.Length >= 2)
                {
                    double.TryParse(strArray[0], out result1);
                    double.TryParse(strArray[1], out result2);
                }
            }
            BitmapImage bitmapImage1;

            if (backgroundCreation)
            {
                BitmapImage bitmapImage2 = new BitmapImage();
                int         num1         = 18;
                bitmapImage2.CreateOptions = ((BitmapCreateOptions)num1);
                int num2 = 1;
                bitmapImage2.DecodePixelType = ((DecodePixelType)num2);
                bitmapImage1 = bitmapImage2;
            }
            else
            {
                BitmapImage bitmapImage2 = new BitmapImage();
                int         num1         = 2;
                bitmapImage2.CreateOptions = ((BitmapCreateOptions)num1);
                int num2 = 1;
                bitmapImage2.DecodePixelType = ((DecodePixelType)num2);
                bitmapImage1 = bitmapImage2;
            }
            if (container.Height > 0.0 && container.Width > 0.0)
            {
                if (result1 == 0.0 || result2 == 0.0)
                {
                    bitmapImage1.DecodePixelHeight = ((int)container.Height);
                }
                else
                {
                    Rect fill = RectangleUtils.ResizeToFill(new Rect(0.0, 0.0, container.Width, container.Height), new Size(result1, result2));
                    // ISSUE: explicit reference operation
                    bitmapImage1.DecodePixelWidth = ((int)((Rect)@fill).Width);
                    // ISSUE: explicit reference operation
                    bitmapImage1.DecodePixelHeight = ((int)((Rect)@fill).Height);
                }
            }
            else
            {
                bitmapImage1.DecodePixelHeight = 300;
            }
            return(bitmapImage1);
        }
示例#4
0
        /// <summary>
        /// Resolves the parameter value in the URI query string.
        /// </summary>
        /// <param name="uri">The URI with the query string which contains the parameter value.</param>
        public object Resolve(Uri uri)
        {
            if (uri == null)
            {
                throw Error.ArgumentNull("uri");
            }

            return(Resolve(UriExtensions.ParseQueryString(uri)));
        }
示例#5
0
        private static SearchParams ParseQueryString(ILocalhost localhost, Uri searchUri)
        {
            Uri absoluteUri = localhost.Absolute(searchUri);
            NameValueCollection keysCollection = UriExtensions.ParseQueryString(absoluteUri);

            IEnumerable <Tuple <string, string> > searchValues =
                keysCollection.Keys.Cast <string>()
                .Select(k => new Tuple <string, string>(k, keysCollection[k]));

            return(SearchParams.FromUriParamList(searchValues));
        }
示例#6
0
 private static void AddToCache(Uri uri, Stream stream)
 {
     VeryLowProfileImageLoader.EnsureLRUCache();
     VeryLowProfileImageLoader._lruCache.Add(uri, (Stream)StreamUtils.ReadFully(stream), true);
     stream.Position = 0L;
     if (UriExtensions.ParseQueryString(uri).ContainsKey(VeryLowProfileImageLoader.REQUIRE_CACHING_KEY))
     {
         ImageCache.Current.TrySetImageForUri(uri.OriginalString, (Stream)StreamUtils.ReadFully(stream));
     }
     stream.Position = 0L;
 }
        public async Task <Result> OldSendLoginData(string userName, string password)
        {
            var httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 8_1_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B440 Safari/600.1.4");
            httpClient.DefaultRequestHeaders.Add("Accept-Language", "ja-jp");
            httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");
            var ohNoTest = await httpClient.GetAsync(new Uri(EndPoints.Login));

            httpClient.DefaultRequestHeaders.Referrer = new Uri("https://auth.api.sonyentertainmentnetwork.com/login.jsp?service_entity=psn&request_theme=liquid");
            httpClient.DefaultRequestHeaders.Add("Origin", "https://auth.api.sonyentertainmentnetwork.com");
            var nameValueCollection = new Dictionary <string, string>
            {
                { "params", "c2VydmljZV9lbnRpdHk9cHNuJnJlcXVlc3RfdGhlbWU9bGlxdWlkJmF1dGhlbnRpY2F0aW9uX2Vycm9yPXRydWU=" },
                { "rememberSignIn", "On" },
                { "j_username", userName },
                { "j_password", password },
            };

            var form     = new FormUrlEncodedContent(nameValueCollection);
            var response = await httpClient.PostAsync(EndPoints.LoginPost, form);

            if (!response.IsSuccessStatusCode)
            {
                return(new Result(false, null, null));
            }

            ohNoTest = await httpClient.GetAsync(new Uri(EndPoints.Login));

            var codeUrl     = ohNoTest.RequestMessage.RequestUri;
            var queryString = UriExtensions.ParseQueryString(codeUrl.ToString());

            if (queryString.ContainsKey("authentication_error"))
            {
                return(new Result(false, null, null));
            }
            if (!queryString.ContainsKey("targetUrl"))
            {
                return(new Result(false, null, null));
            }
            queryString = UriExtensions.ParseQueryString(WebUtility.UrlDecode(queryString["targetUrl"]));
            if (!queryString.ContainsKey("code"))
            {
                return(null);
            }

            var authManager = new AuthenticationManager();
            var authEntity  = await authManager.RequestAccessToken(queryString["code"]);

            return(!string.IsNullOrEmpty(authEntity) ? new Result(true, null, authEntity) : new Result(false, null, null));
        }
示例#8
0
文件: LREST.cs 项目: tren01t/C-Sharp
        public static async Task <string> Post(Uri uri, string contentToPost, string headers, string expectedReturnedFileExtention)
        {
            string retVal = "";

            try
            {
                //MimeSharp.Mime mime = new MimeSharp.Mime();

                using (HttpClient client = new HttpClient())
                {
                    NameValueCollection headerCollection = UriExtensions.ParseQueryString(new Uri(uri.AbsoluteUri + "?" + headers));
                    //string contentType = mime.Lookup(expectedReturnedFileExtention);// "application/x-www-form-urlencoded";
                    string contentType = "application/json"; //"application/x-www-form-urlencoded";

                    HttpContent postRequestContent = new StringContent(contentToPost, Encoding.UTF8, contentType);

                    //requestContent.Headers.Add("Authorization", "Bearer " + _access_token);

                    postRequestContent.Headers.TryAddWithoutValidation("If-None-Match", "\"doesnt-match-anything\"");
                    foreach (string h in headerCollection)
                    {
                        postRequestContent.Headers.Add(h, headerCollection[h]);
                        //Console.WriteLine(headerCollection[h]);
                    }

                    HttpResponseMessage response = await client.PostAsync(uri, postRequestContent);

                    //response.EnsureSuccessStatusCode();

                    if (response.IsSuccessStatusCode)
                    {
                        retVal = await response.Content.ReadAsStringAsync();

                        //Console.WriteLine("sent");
                    }
                    else
                    {
                        retVal = "Error: " + response.StatusCode;
                    }
                }
            }
            catch (Exception error)
            {
                retVal = "Error: " + error.Message;
            }

            return(retVal);
        }
示例#9
0
        protected override async void OnActivated(IActivatedEventArgs args)
        {
            base.OnActivated(args);
            if (args.Kind != ActivationKind.Protocol)
            {
                return;
            }
            var eventArgs = args as ProtocolActivatedEventArgs;

            if (eventArgs == null)
            {
                return;
            }
            IReadOnlyDictionary <string, string> queryString = UriExtensions.ParseQueryString(eventArgs.Uri);

            if (!queryString.ContainsKey("authCode"))
            {
                return;
            }
            var  authManager = new AuthenticationManager();
            bool test        = await authManager.RequestAccessToken(queryString["authCode"]);

            if (!test)
            {
                return;
            }
            bool loginTest = await LoginTest();

            if (!loginTest)
            {
                return;
            }
            UserAccountEntity.User user = await authManager.GetUserEntity(UserAccountEntity);

            if (user == null)
            {
                return;
            }
            UserAccountEntity.SetUserEntity(user);
            var rootFrame = Window.Current.Content as Frame;

            if (rootFrame != null)
            {
                rootFrame.Navigate(typeof(MainPage));
            }
        }
示例#10
0
        public static JObject ParseJsonOrUrlEncodedParams(string paramString)
        {
            if (string.IsNullOrWhiteSpace(paramString))
            {
                return(new JObject());
            }

            bool    parseSuccess = false;
            JObject result       = null;

            try
            {
                result       = JObject.Parse(paramString);
                parseSuccess = true;
            }
            catch (JsonReaderException)
            {
            }

            if (!parseSuccess)
            {
                // This is a hack, and it feels bad.
                var parsedParams = UriExtensions.ParseQueryString(
                    new Uri(
                        string.Format(CultureInfo.CurrentCulture,
                                      "http://tempuri.org/?{0}", paramString)));

                result = JObject.FromObject(parsedParams.AllKeys
                                            .ToDictionary(
                                                k => k,
                                                k => parsedParams[k]
                                                ));

                parseSuccess = true;
            }

            foreach (var prop in result.Properties())
            {
                prop.buildParameterPlaceholders();
            }

            return(result);
        }
示例#11
0
        private static string GetCanonicalQueryParams(HttpRequestMessage request)
        {
            var values = new SortedDictionary <string, string>();

            var querystring = UriExtensions.ParseQueryString(request.RequestUri);

            foreach (var key in querystring.AllKeys)
            {
                if (key == null)//Handles keys without values
                {
                    values.Add(Uri.EscapeDataString(querystring[key]), $"{Uri.EscapeDataString(querystring[key])}=");
                }
                else
                {
                    // Query params must be escaped in upper case (i.e. "%2C", not "%2c").
                    values.Add(Uri.EscapeDataString(key), $"{Uri.EscapeDataString(key)}={Uri.EscapeDataString(querystring[key])}");
                }
            }

            var queryParams          = values.Select(a => a.Value);
            var canonicalQueryParams = string.Join("&", queryParams);

            return(canonicalQueryParams);
        }
示例#12
0
        private async Task HandleRequestAsync(HttpListenerContext context)
        {
            var              successful = false;
            ulong            steamId    = 0;
            SteamOpenIdState state      = null;

            try
            {
                var  request = context.Request;
                var  qs      = request.QueryString;
                Guid a;
                if (!Guid.TryParse(qs["a"] ?? "", out a))
                {
                    //request failed
                    return;
                }


                if (!_states.TryRemove(a, out state))
                {
                    //failed to get state
                    return;
                }

                var query = UriExtensions.ParseQueryString(state.ReturnTo);

                if (request.Url.Scheme != state.ReturnTo.Scheme ||
                    request.Url.Authority != state.ReturnTo.Authority ||
                    request.Url.AbsolutePath != state.ReturnTo.AbsolutePath ||
                    query.AllKeys.Any(x => qs[x] == null || qs[x].Equals(query[x], StringComparison.Ordinal) == false) ||
                    qs["openid.mode"]?.Equals("id_res") != true ||
                    qs["openid.claimed_id"]?.StartsWith(state.Authority) != true)
                {
                    //assertions failed
                    return;
                }

                var r = new Regex(@"/openid/id/(?<steamid>\d+)$", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                var m = r.Match(qs["openid.claimed_id"]);
                if (!m.Success)
                {
                    //failed to get steamid
                    return;
                }

                if (!ulong.TryParse(m.Groups["steamid"].Value, NumberStyles.None, CultureInfo.InvariantCulture, out steamId))
                {
                    return;
                }
                successful = true;

                //openid/
                //?openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0
                //&openid.mode=id_res
                //&openid.op_endpoint=https%3A%2F%2Fsteamcommunity.com%2Fopenid%2Flogin
                //&openid.claimed_id=http%3A%2F%2Fsteamcommunity.com%2Fopenid%2Fid%2F76561198005371608
                //&openid.identity=http%3A%2F%2Fsteamcommunity.com%2Fopenid%2Fid%2F76561198005371608
                //&openid.return_to=http%3A%2F%2F62.63.229.45%3A7331%2Fopenid%2F
                //&openid.response_nonce=2017-02-05T18%3A20%3A46ZwFvmnCumgCkT9IWOoIDpaJLc6%2Bs%3D
                //&openid.assoc_handle=1234567890
                //&openid.signed=signed%2Cop_endpoint%2Cclaimed_id%2Cidentity%2Creturn_to%2Cresponse_nonce%2Cassoc_handle
                //&openid.sig=Cpo83xgHcMqzVOyQqe693s%2FRQO4%3D
            }
            finally
            {
                Task task;
                _ongoingTasks.TryRemove(context.Request.RequestTraceIdentifier, out task);
                if (state != null)
                {
                    OnSteamOpenIdCallback(successful, steamId, state.DiscordUserId);

                    if (_getHtmlContent != null)
                    {
                        var content = await _getHtmlContent(successful, steamId, state.DiscordUserId);

                        var buffer = Encoding.UTF8.GetBytes(content);
                        context.Response.ContentLength64 = buffer.Length;
                        await context.Response.OutputStream.WriteAsync(buffer, 0, buffer.Length);

                        context.Response.OutputStream.Close();
                    }
                }
            }
        }
        public async Task <Result> SendLoginData(string username, string password)
        {
            try
            {
                using (var httpClient = new HttpClient())
                {
                    // Set the default headers
                    // These are needed so the PSN Auth server will accept our username and password
                    // and hand us a token
                    // If we don't, we will get an HTML page back with no codes

                    httpClient.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                    httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13C75 PlayStation Messages App/3.10.67");
                    httpClient.DefaultRequestHeaders.Add("Accept-Language", "ja-jp");
                    httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");
                    httpClient.DefaultRequestHeaders.Referrer = new Uri(EndPoints.AuthReferrer);
                    httpClient.DefaultRequestHeaders.Add("Origin", "https://id.sonyentertainmentnetwork.com");

                    var nameValueCollection = new Dictionary <string, string>
                    {
                        { "authentication_type", "password" },
                        { "client_id", EndPoints.LoginKey },
                        { "username", username },
                        { "password", password },
                    };
                    var form = new FormUrlEncodedContent(nameValueCollection);

                    // Send out initial request to get an "SSO Cookie", which is actually in JSON too. For some reason.
                    var response = await httpClient.PostAsync(EndPoints.SsoCookie, form);

                    if (!response.IsSuccessStatusCode)
                    {
                        return(ErrorHandler.CreateErrorObject(new Result(), "Username/Password Failed", "Auth"));
                    }

                    var responseJson = await response.Content.ReadAsStringAsync();

                    // Get the npsso key. Add the client id, scope, and service entity and send it back.
                    var authorizeCheck = JsonConvert.DeserializeObject <AuthorizeCheck>(responseJson);
                    authorizeCheck.client_id      = EndPoints.LoginKey;
                    authorizeCheck.scope          = EndPoints.Scope;
                    authorizeCheck.service_entity = "urn:service-entity:psn";

                    var json          = JsonConvert.SerializeObject(authorizeCheck);
                    var stringContent = new StringContent(json, Encoding.UTF8, "application/json");

                    // Call auth check so we can continue the flow...
                    await httpClient.PostAsync(EndPoints.AuthorizeCheck, stringContent);

                    // Get our code, so we can get our access tokens.
                    var testResult = await httpClient.GetAsync(new Uri(EndPoints.Login));

                    var codeUrl     = testResult.Headers.Location;
                    var queryString = UriExtensions.ParseQueryString(codeUrl.ToString());
                    if (queryString.ContainsKey("authentication_error"))
                    {
                        return(ErrorHandler.CreateErrorObject(new Result(), "Failed to get OAuth Code (Authentication_error)", "Auth"));
                    }

                    if (!queryString.ContainsKey("code"))
                    {
                        return(ErrorHandler.CreateErrorObject(new Result(), "Failed to get OAuth Code (No code)", "Auth"));
                    }

                    var authManager = new AuthenticationManager();
                    var authEntity  = await authManager.RequestAccessToken(queryString["code"]);

                    return(!string.IsNullOrEmpty(authEntity) ? new Result(true, null, authEntity) : new Result(false, null, null));
                }
            }
            catch (Exception ex)
            {
                // All else fails, send back the stack trace.
                return(ErrorHandler.CreateErrorObject(new Result(), ex.Message, ex.StackTrace));
            }
        }