public Data.PagedDataRequest Create(Uri requestUri)
        {
            int? pageNumber;
            int? pageSize;

            try
            {
                var valueCollection = requestUri.ParseQueryString();

                pageNumber =
                    PrimitiveTypeParser.Parse<int?>(valueCollection[Constants.CommonParameterNames.PageNumber]);

                pageSize = PrimitiveTypeParser.Parse<int?>(valueCollection[Constants.CommonParameterNames.PageSize]);
            }
            catch(Exception e)
            {
                _log.Error("Error Parsing input", e);
                throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
            }

            pageNumber = pageNumber.GetBoundedValue(Constants.Paging.DefaultPageNumber, Constants.Paging.MinPageNumber);
            pageSize = pageSize.GetBoundedValue(DefaultPageSize, Constants.Paging.MinPageSize, MaxPageSize);


            return new PagedDataRequest(pageNumber.Value, pageSize.Value);
        }
 public static Response Execute(Uri url, Func<ISchedulerWrapper> getScheduler)
 {
     var scheduler = getScheduler();
     var p = GetMethodParameters(url.ParseQueryString());
     p.method.Invoke(scheduler, p.parameters.ToArray());
     return new Response.RedirectResponse(p.redirect);
 }
 public static Response Execute(Uri url)
 {
     var querystring = url.ParseQueryString();
     var resource = querystring["r"];
     resource = string.Format("{0}.Resources.{1}", assembly.FullName.Split(',')[0], resource);
     var content = ReadResource(resource);
     return new Response.ContentResponse(content: content, contentType: querystring["t"]);
 }
Esempio n. 4
0
        private void SelectedCurrencyLinkChanged(Uri link)
        {
            string currencyName;
            link.ParseQueryString().TryGetValue("Name", out currencyName);

            var selectedCurrency = _context.Currencies.FirstOrDefault(x => x.Name == currencyName);

            if (selectedCurrency != null)
                Messenger.Default.Send(selectedCurrency, "currencyChangedMsg");
        }
Esempio n. 5
0
	    public virtual MvxShowViewModelRequest GetRequestFromXamlUri(Uri viewUri)
		{
	        var parsed = viewUri.ParseQueryString();

	        string queryString;
            if (!parsed.TryGetValue(QueryParameterKeyName, out queryString))
			    throw new MvxException("Unable to find incoming MvxShowViewModelRequest");

			var text = Uri.UnescapeDataString(queryString);
			return JsonConvert.DeserializeObject<MvxShowViewModelRequest>(text);
		}
        public virtual MvxViewModelRequest GetRequestFromXamlUri(Uri viewUri)
        {
            var parsed = viewUri.ParseQueryString();

            string queryString;
            if (!parsed.TryGetValue(QueryParameterKeyName, out queryString))
                throw new MvxException("Unable to find incoming MvxViewModelRequest");

            var converter = Mvx.Resolve<IMvxNavigationSerializer>();
            return converter.Serializer.DeserializeObject<MvxViewModelRequest>(queryString);
        }
 public static Response Execute(Uri url, Func<ISchedulerWrapper> getScheduler)
 {
     var scheduler = getScheduler();
     var qs = url.ParseQueryString();
     var highlight = qs["highlight"];
     var group = qs["group"];
     var triggers = GetTriggers(scheduler, group);
     var paused = scheduler.IsTriggerGroupPaused(group);
     var v = Views.Views.TriggerGroup(group, paused, url.PathAndQuery, highlight, triggers);
     return new Response.XDocumentResponse(Helpers.XHTML(v));
 }
 public static Response Execute(Uri url, Func<ISchedulerWrapper> getScheduler)
 {
     var scheduler = getScheduler();
     var querystring = url.ParseQueryString();
     var highlight = querystring["highlight"];
     var group = querystring["group"];
     var job = querystring["job"];
     var jobKey = new JobKey(job, group);
     var triggers = GetTriggers(scheduler, jobKey);
     var m = new TriggersByJobModel(triggers, url.PathAndQuery, group, job, highlight);
     return new Response.XDocumentResponse(Helpers.XHTML(Views.Views.TriggersByJob(m)));
 }
Esempio n. 9
0
        public static async Task<string> Authenticate()
        {
            var startURI = new Uri(START_URL);
            var endURI = new Uri(END_URL);
            string result;

            var webAuthResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startURI, endURI);

            switch (webAuthResult.ResponseStatus)
            {
                case WebAuthenticationStatus.Success:
                    result = webAuthResult.ResponseData.ToString();
                    break;
                case WebAuthenticationStatus.ErrorHttp:
                    result = webAuthResult.ResponseData.ToString();
                    throw new Exception(result);
                default:
                    throw new Exception("Error :(");
            }
            var resultURI = new Uri(result);
            var query = resultURI.ParseQueryString();
            var code = query["code"];
            var tokenURL = "https://api.slack.com/api/oauth.access?code="
                + Uri.EscapeUriString(code)
                + "&client_id=" + Uri.EscapeUriString(CLIENT_ID)
                + "&client_secret=" + Uri.EscapeUriString(CLIENT_SECRET);
            var tokenURI = new Uri(tokenURL);
            var httpClient = new HttpClient();
            string tokenResponse;
            try
            {
                tokenResponse = await httpClient.GetStringAsync(tokenURI);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                httpClient.Dispose();
            }
            JsonObject tokenObject;
            if (!JsonObject.TryParse(tokenResponse, out tokenObject))
            {
                throw new Exception("Couldn't parse HTTP response. Try again later.");
            }
            if (!tokenObject.GetNamedBoolean("ok"))
            {
                throw new Exception("You are not authorized to access this team.");
            }
            return tokenObject.GetNamedString("access_token");
        }
Esempio n. 10
0
    /// <summary>
    /// Parses the authentication response URI and creates the response object.
    /// </summary>
    /// <param name="uri">The URI where the user has been redirected to after authentication.</param>
    /// <returns></returns>
    public AuthenticationResponse ParseAuthenticationResponseUri(Uri uri)
    {
      Dictionary<string, string> queryParams = uri.ParseQueryString();
      string code = null;
      string error = null;
      string state = null;

      queryParams.TryGetValue("code", out code);
      queryParams.TryGetValue("error", out error);
      queryParams.TryGetValue("state", out state);

      return new AuthenticationResponse() { Code = code, Error = error, State = state };
    }
        private static int GetOrderKey(
            IHttpRouteData routeData, Uri requestUri)
        {
            object orderKeyString;
            if (routeData.Values.TryGetValue("key", out orderKeyString)) {

                return int.Parse(orderKeyString.ToString());
            }

            // It's now sure that query string has the shipmentKey value
            var quesryString = requestUri.ParseQueryString();
            return int.Parse(quesryString["key"]);
        }
Esempio n. 12
0
 public static NameValueCollection FromForm(this IWebResponse response)
 {
     if (response == null)
     {
         throw new ArgumentNullException("response");
     }
     using (var stream = response.Response.GetResponseStream())
     using (var reader = new StreamReader(stream))
     {
         string formData = reader.ReadToEnd();
         Uri fakeUri = new Uri("http://localhost/?" + formData);
         return fakeUri.ParseQueryString();
     }
 }
        public static OAuthRequest Parse(Uri uri)
        {
            NameValueCollection queryString = uri.ParseQueryString();
            string responseType = queryString.Get("response_type");
            string clientId = queryString.Get("client_id");
            string state = queryString.Get("state");
            string scope = queryString.Get("scope");
            string jwt = queryString.Get("jwt_token");
            var redirectUri = new Uri(queryString.Get("redirect_uri"), UriKind.Absolute);
            
            var originalUri = uri.ToString().Replace("&jwt_token=" + jwt, "");

            return new OAuthRequest(responseType, clientId, state, scope, redirectUri, jwt, originalUri);
        }
 public static Response Execute(Uri url)
 {
     var thisUrl = url.PathAndQuery.Split('?')[0];
     var qs = url.ParseQueryString();
     var pageSize = GetPageSize(qs);
     var pagination = new PaginationInfo(
         firstItemIndex: GetStartIndex(qs),
         pageSize: pageSize,
         totalItemCount: logsQ.Count(),
         pageUrl: "log.ashx?start=!0&max=" + pageSize);
     var logs = logsQ.Skip(pagination.FirstItemIndex).Take(pagination.PageSize).ToList();
     var v = GetView(qs.AllKeys);
     var view = v.Value(logs, pagination, thisUrl);
     return new Response.XDocumentResponse(view, v.Key);
 }
        public ActionResult Callback()
        {
            string input;
            using (var reader = new StreamReader(Request.InputStream))
            {
                input = reader.ReadToEnd();
            }

            string locationBase = string.Format("{0}/auth/broker/end",
                                                Request.Url.GetComponents(UriComponents.SchemeAndServer,
                                                                          UriFormat.Unescaped));
            var inputInQueryStringUri = new Uri(locationBase + "?" + input);
            NameValueCollection tokenValues = inputInQueryStringUri.ParseQueryString();
            string tokenData = tokenValues["wresult"];

            //Validate SWT token
            var tokenSerializer = new WSTrustFeb2005ResponseSerializer();
            RequestSecurityTokenResponse requestSecrityTokenResponse =
                tokenSerializer.ReadXml(new XmlTextReader(new StringReader(tokenData)),
                                        new WSTrustSerializationContext());

            var simpleWebTokenHandler = new SimpleWebTokenHandler("https://" + _registrationService.ServiceNamespace + ".accesscontrol.windows.net/", _swtSigningKey);
            var securityToken = simpleWebTokenHandler.ReadToken(requestSecrityTokenResponse.RequestedSecurityToken.SecurityTokenXml.InnerText) as SimpleWebToken;
            simpleWebTokenHandler.ValidateToken(securityToken, _acsRealm);

            //Create delegation in ACS
            var authServerIdentifier = securityToken.Claims.FirstOrDefault(c => c.ClaimType == ClaimTypes.NameIdentifier);
            var authServerIdentity = new AuthorizationServerIdentity
                                         {
                                             NameIdentifier = authServerIdentifier.Value,
                                             IdentityProvider = authServerIdentifier.Issuer
                                         };

            //todo: Check if we can add some claims (role claims) to the scope
            string code = _registrationService.GetAuthorizationCode(_clientId, authServerIdentity, "scope");

            //todo: use OAuth parameter names in the return URL
            //return the token
            string location = string.Format("{0}?acsToken={1}", locationBase, code);

            Response.StatusCode = (int)HttpStatusCode.Redirect;
            Response.Headers.Add("Location", location);
            Response.End();

            return null;
        }
 public static void HandleTryAppServiceResponse(HttpContextBase context)
 {
     if (context.Request.RawUrl.StartsWith("/try") && context.Request.Params["cookie"] != null)
     {
         var tryAppServiceToken = context.Request.Params["cookie"];
         var state = context.Request.Params["state"];
         var uri = new Uri(state);
         var querystring = uri.ParseQueryString();
         context.Response.SetCookie(new HttpCookie("TryAppServiceToken", tryAppServiceToken));
         context.Response.SetCookie(new HttpCookie("templateId", querystring["templateId"]));
         context.Response.SetCookie(new HttpCookie("provider", querystring["provider"]));
         context.Response.SetCookie(new HttpCookie("functionName", querystring["functionName"]));
         context.Response.RedirectLocation = "/try";
         context.Response.StatusCode = 302;
         context.Response.End();
     }
 }
 public static Response Execute(Uri url, Func<ISchedulerWrapper> getScheduler)
 {
     var scheduler = getScheduler();
     var querystring = url.ParseQueryString();
     var group = querystring["group"];
     var jobNames = scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals(group));
     var runningJobs = scheduler.GetCurrentlyExecutingJobs();
     var jobs = jobNames.Select(j => {
         var job = scheduler.GetJobDetail(j);
         var interruptible = typeof (IInterruptableJob).IsAssignableFrom(job.JobType);
         var jobContext = runningJobs.FirstOrDefault(r => r.JobDetail.Key.ToString() == job.Key.ToString());
         return new JobWithContext(job, jobContext, interruptible);
     });
     var paused = scheduler.IsJobGroupPaused(group);
     var highlight = querystring["highlight"];
     var view = Views.Views.JobGroup(group, paused, highlight, url.PathAndQuery, jobs);
     return new Response.XDocumentResponse(Helpers.XHTML(view));
 }
Esempio n. 18
0
        private static string CalculateCanonicalRequestHash(string httpMethod, string url, IDictionary<string, string> httpHeaders, out string signedHeaders)
        {
            var httpMethodToUpper = httpMethod.ToUpper();
            var isGet = httpMethodToUpper == "GET";

            var uri = new Uri(url);
            var queryStringCollection = uri.ParseQueryString();

            var canonicalUri = uri.AbsolutePath;

            var queryString = (
                from string parameter in queryStringCollection
                select new KeyValuePair<string, string>(parameter, queryStringCollection.Get(parameter))
                );

            var canonicalQueryString = queryString
                .OrderBy(x => x.Key)
                .Aggregate(string.Empty, (current, parameter) => current + string.Format("{0}={1}&", parameter.Key.ToLower(), parameter.Value.Trim()));

            if (canonicalQueryString.EndsWith("&"))
                canonicalQueryString = canonicalQueryString.Substring(0, canonicalQueryString.Length - 1);

            var headers = httpHeaders
                .Where(x => isGet == false || x.Key.StartsWith("Date", StringComparison.InvariantCultureIgnoreCase) == false)
                .OrderBy(x => x.Key);

            var canonicalHeaders = headers
                .Aggregate(string.Empty, (current, parameter) => current + string.Format("{0}:{1}\n", parameter.Key.ToLower(), parameter.Value.Trim()));

            signedHeaders = headers
                .Aggregate(string.Empty, (current, parameter) => current + parameter.Key.ToLower() + ";");

            if (signedHeaders.EndsWith(";"))
                signedHeaders = signedHeaders.Substring(0, signedHeaders.Length - 1);

            using (var hash = SHA256.Create())
            {
                var hashedPayload = httpHeaders["x-amz-content-sha256"];
                var canonicalRequest = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}", httpMethodToUpper, canonicalUri, canonicalQueryString, canonicalHeaders, signedHeaders, hashedPayload);

                return RavenAwsHelper.ConvertToHex(hash.ComputeHash(Encoding.UTF8.GetBytes(canonicalRequest)));
            }
        }
Esempio n. 19
0
        private string ComputeCanonicalizedResource(string url)
        {
            var uri = new Uri(url, UriKind.Absolute);

            var stringToHash = string.Format("/{0}{1}\n", accountName, uri.AbsolutePath);
            var queryStringCollection = uri.ParseQueryString();

            var queryString = (
                from string parameter in queryStringCollection 
                select new KeyValuePair<string, string>(parameter, queryStringCollection.Get(parameter))
                );

            return queryString
                .OrderBy(x => x.Key)
                .Aggregate(stringToHash, (current, parameter) => current + string.Format("{0}:{1}\n", parameter.Key.ToLower(), parameter.Value));
        }
 public virtual ClaimsPrincipal AuthenticateQueryStrings(Uri uri)
 {
     return AuthenticateQueryStrings(uri.ParseQueryString());
 }
        private OfflineEntry GetCacheEntry(Uri uri, Guid requestId)
        {
            var filteredQueryParameters = uri.ParseQueryString()
                .Where(p => p.Key != "_")

                // Sanitize empty values (query string wo value)
                .Select(p => p.Key + (p.Value != null ? "=" : string.Empty) + (string.IsNullOrEmpty(p.Value) ? string.Empty : p.Value));

            var mappedUri = new UriBuilder(uri);
            mappedUri.Query = string.Join("&", filteredQueryParameters);

            // TODO: review if trimming trailing slash is correct
            var flatString = mappedUri.Uri.ToString().TrimEnd('/');

            OfflineEntry entry = null;
            lock (this.cacheIndex)
            {
                if (!this.cacheIndex.TryGetValue(flatString, out entry))
                {
                    entry = new OfflineEntry { RequestId = requestId, Key = flatString };
                }
            }

            return entry;
        }
Esempio n. 22
0
        public Uri MakeUriFor(ReadOnlyCollection<Expression> arguments, UrlHelper urlHelper)
        {
            var argumentValues = ParameterHandlers.Any() ? ComputeRouteMap(ComputeArgumentValues(arguments)) : EmptyMap;
            var mapForUrlHelper = new Dictionary<string, object>();
            var mapForQueryString = new Dictionary<string, IEnumerable>();
            if (urlHelper.Request.GetRouteData() != null && urlHelper.Request.GetRouteData().GetSubRoutes() != null)
            {
                foreach (var p in urlHelper.Request.GetRouteData().GetSubRoutes().SelectMany(r => r.Values))
                {
                    mapForUrlHelper[p.Key] = p.Value;
                }
            }
            foreach (var p in argumentValues)
            {
                var arr = p.Value as IEnumerable;
                if (arr == null || p.Value is string)
                {
                    mapForUrlHelper[p.Key] = p.Value;
                }
                else
                {
                    mapForQueryString[p.Key] = arr;
                }
            }

            var routeEntry = _routeSelector(urlHelper.Request, RouteEntries);
            var uri = new Uri(urlHelper.Link(routeEntry.Name, mapForUrlHelper));
            if(mapForQueryString.Count == 0)
            {
                return uri;
            }
            var uriBuilder = new UriBuilder(uri);
            var query = uri.ParseQueryString();
            foreach(var pair in mapForQueryString)
            {
                var key = pair.Key;
                var arr = pair.Value;
                foreach(var value in arr)
                {
                    query.Add(key, Convert.ToString(value, CultureInfo.InvariantCulture));
                }
            }
            uriBuilder.Query = query.ToString();
            return uriBuilder.Uri;
        }
Esempio n. 23
0
 public static void IsRedirectedToCookiesLogin(Uri requestUri, string protectedResourceUri, string message, string queryParameterName = "ReturnUrl")
 {
     Assert.True(requestUri.AbsolutePath.EndsWith("/Auth/CookiesLogin"), message);
     Assert.Equal<string>(new Uri(protectedResourceUri).AbsolutePath, requestUri.ParseQueryString()[queryParameterName]);
 }
Esempio n. 24
0
        public void Security_AuthorizeEndpointTests(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                var applicationUrl = deployer.Deploy(hostType, AuthServerHappyPathConfiguration);

                IDisposable clientEndpoint = null;
                try
                {
                    clientEndpoint = WebApp.Start(Client_Redirect_Uri, app => app.Run(context => { return context.Response.WriteAsync(context.Request.QueryString.Value); }));

                    string tokenEndpointUri = applicationUrl + "TokenEndpoint";
                    var basicClient = new HttpClient();
                    var headerValue = Convert.ToBase64String(Encoding.Default.GetBytes(string.Format("{0}:{1}", "123", "invalid")));
                    basicClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", headerValue);

                    HttpClient httpClient = new HttpClient();
                    string requestUri = null;
                    Uri landingUri = null;
                    Uri applicationUri = new Uri(applicationUrl);
                    HttpResponseMessage httpResponseMessage = null;

                    //Happy path - response_type:code
                    requestUri = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", Client_Redirect_Uri, "scope1", "validstate");
                    landingUri = httpClient.GetAsync(requestUri).Result.RequestMessage.RequestUri;
                    Assert.Equal<string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
                    Assert.NotNull(landingUri.ParseQueryString()["code"]);
                    Assert.Equal<string>("validstate", landingUri.ParseQueryString()["state"]);

                    //Happy path - response_type:token
                    requestUri = AuthZ.CreateAuthZUri(applicationUrl, "token", "123", Client_Redirect_Uri, "scope1", "validstate");
                    landingUri = httpClient.GetAsync(requestUri).Result.RequestMessage.RequestUri;
                    landingUri = new Uri(landingUri.AbsoluteUri.Replace('#', '?'));
                    Assert.Equal<string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
                    Assert.NotNull(landingUri.ParseQueryString()["access_token"]);
                    Assert.NotNull(landingUri.ParseQueryString()["expires_in"]);
                    Assert.Equal<string>("bearer", landingUri.ParseQueryString()["token_type"]);
                    Assert.Equal<string>("validstate", landingUri.ParseQueryString()["state"]);

                    //Invalid redirect URI - pass error to application
                    requestUri = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", "invalid_uri_passonerror", "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.Equal<string>("error: invalid_request\r\n", httpResponseMessage.Content.ReadAsStringAsync().Result);
                    Assert.True(httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Authority).StartsWith(applicationUri.GetLeftPart(UriPartial.Authority)), "Should not be redirected on invalid redirect_uri");

                    //Invalid redirect URI - Display error by middleware
                    requestUri = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", "invalid_uri_displayerror", "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.True(httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Authority).StartsWith(applicationUri.GetLeftPart(UriPartial.Authority)), "Should not be redirected on invalid redirect_uri");
                    Assert.True(httpResponseMessage.Content.ReadAsStringAsync().Result.StartsWith("error: invalid_request"), "Did not receive an error for an invalid redirect_uri");

                    //What happens if we don't set Validated explicitly. Send an invalid clientId => We don't set Validated for this case.
                    requestUri = AuthZ.CreateAuthZUri(applicationUrl, "token", "invalidClient", Client_Redirect_Uri, "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.True(httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Authority).StartsWith(applicationUri.GetLeftPart(UriPartial.Authority)), "Should not be redirected on invalid redirect_uri");
                    Assert.True(httpResponseMessage.Content.ReadAsStringAsync().Result.StartsWith("error: invalid_request"), "Did not receive an error for an invalid redirect_uri");

                    //OnValidateAuthorizeRequest - Rejecting a request. Send an invalid state as we validate it there. Client should receive all the error code & description that we send
                    requestUri = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", Client_Redirect_Uri, "scope1", "invalidstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    landingUri = httpResponseMessage.RequestMessage.RequestUri;
                    Assert.Equal<string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
                    Assert.Equal<string>("state.invalid", landingUri.ParseQueryString()["error"]);
                    Assert.Equal<string>("state.invaliddescription", landingUri.ParseQueryString()["error_description"]);
                    Assert.Equal<string>("state.invaliduri", landingUri.ParseQueryString()["error_uri"]);
                    Assert.True(httpResponseMessage.Content.ReadAsStringAsync().Result.StartsWith("error=state.invalid&error_description=state.invaliddescription&error_uri=state.invaliduri"), "Did not receive an error when provider did not set Validated");

                    //Missing response_type
                    requestUri = AuthZ.CreateAuthZUri(applicationUrl, null, "123", Client_Redirect_Uri, "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.Equal<string>(Client_Redirect_Uri, httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Path));
                    Assert.Equal<string>("invalid_request", httpResponseMessage.RequestMessage.RequestUri.ParseQueryString()["error"]);

                    //Unsupported response_type
                    requestUri = AuthZ.CreateAuthZUri(applicationUrl, "invalid_response_type", "123", Client_Redirect_Uri, "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.Equal<string>(Client_Redirect_Uri, httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Path));
                    Assert.Equal<string>("unsupported_response_type", httpResponseMessage.RequestMessage.RequestUri.ParseQueryString()["error"]);

                    //Missing client_id
                    requestUri = AuthZ.CreateAuthZUri(applicationUrl, "token", null, Client_Redirect_Uri, "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.True(httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Authority).StartsWith(applicationUri.GetLeftPart(UriPartial.Authority)), "Should not be redirected on invalid redirect_uri");
                    Assert.True(httpResponseMessage.Content.ReadAsStringAsync().Result.StartsWith("error: invalid_request"), "Did not receive an error for an invalid redirect_uri");

                    //Missing state - Should succeed
                    requestUri = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", Client_Redirect_Uri, "scope1", null);
                    landingUri = httpClient.GetAsync(requestUri).Result.RequestMessage.RequestUri;
                    Assert.Equal<string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
                    Assert.NotNull(landingUri.ParseQueryString()["code"]);
                    Assert.Equal<bool>(false, landingUri.ParseQueryString().ContainsKey("state"));

                    //Token endpoint tests
                    //Invalid client (client_id, client_secret) - As form parameters
                    var formContent = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "invalid") });
                    var responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    var jToken = JToken.Parse(responseMessage);
                    Assert.Equal<string>("invalid_client", jToken.SelectToken("error").Value<string>());

                    //Invalid client (client_id, client_secret) - As Basic auth headers
                    responseMessage = basicClient.GetAsync(tokenEndpointUri).Result.Content.ReadAsStringAsync().Result;
                    jToken = JToken.Parse(responseMessage);
                    Assert.Equal<string>("invalid_client", jToken.SelectToken("error").Value<string>());

                    //grant_type=authorization_code - invalid code being sent
                    formContent = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "authorization_code"), new kvp("code", "InvalidCode"), new kvp("redirect_uri", Client_Redirect_Uri) });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken = JToken.Parse(responseMessage);
                    Assert.Equal<string>("invalid_grant", jToken.SelectToken("error").Value<string>());

                    //grant_type=authorization_code - Full scenario
                    requestUri = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", Client_Redirect_Uri, "scope1", "validstate");
                    landingUri = httpClient.GetAsync(requestUri).Result.RequestMessage.RequestUri;
                    Assert.Equal<string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
                    Assert.NotNull(landingUri.ParseQueryString()["code"]);
                    Assert.Equal<string>("validstate", landingUri.ParseQueryString()["state"]);
                    formContent = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "authorization_code"), new kvp("code", landingUri.ParseQueryString()["code"]), new kvp("redirect_uri", Client_Redirect_Uri) });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken = JToken.Parse(responseMessage);
                    Assert.NotNull(jToken.SelectToken("access_token").Value<string>());
                    Assert.Equal<string>("bearer", jToken.SelectToken("token_type").Value<string>());
                    Assert.NotNull(jToken.SelectToken("expires_in").Value<string>());
                    Assert.Equal<string>("value1", jToken.SelectToken("param1").Value<string>());
                    Assert.Equal<string>("value2", jToken.SelectToken("param2").Value<string>());
                    Assert.NotNull(jToken.SelectToken("refresh_token").Value<string>());

                    //grant_type=password -- Resource owner credentials -- Invalid credentials
                    formContent = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "password"), new kvp("username", "user1"), new kvp("password", "invalid"), new kvp("scope", "scope1 scope2 scope3") });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken = JToken.Parse(responseMessage);
                    Assert.Equal<string>("invalid_grant", jToken.SelectToken("error").Value<string>());

                    //grant_type=password -- Resource owner credentials
                    formContent = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "password"), new kvp("username", "user1"), new kvp("password", "password1"), new kvp("scope", "scope1 scope2 scope3") });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken = JToken.Parse(responseMessage);
                    Assert.NotNull(jToken.SelectToken("access_token").Value<string>());
                    Assert.Equal<string>("bearer", jToken.SelectToken("token_type").Value<string>());
                    Assert.NotNull(jToken.SelectToken("expires_in").Value<string>());
                    Assert.Equal<string>("value1", jToken.SelectToken("param1").Value<string>());
                    Assert.Equal<string>("value2", jToken.SelectToken("param2").Value<string>());
                    Assert.NotNull(jToken.SelectToken("refresh_token").Value<string>());

                    //grant_type=refresh_token -- Use the refresh token issued on the previous call
                    formContent = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "refresh_token"), new kvp("refresh_token", jToken.SelectToken("refresh_token").Value<string>()), new kvp("scope", "scope1 scope2") });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken = JToken.Parse(responseMessage);
                    Assert.NotNull(jToken.SelectToken("access_token").Value<string>());
                    Assert.Equal<string>("bearer", jToken.SelectToken("token_type").Value<string>());
                    Assert.NotNull(jToken.SelectToken("expires_in").Value<string>());
                    Assert.Equal<string>("value1", jToken.SelectToken("param1").Value<string>());
                    Assert.Equal<string>("value2", jToken.SelectToken("param2").Value<string>());
                    Assert.NotNull(jToken.SelectToken("refresh_token").Value<string>());

                    //grant_type=client_credentials - Bug# https://github.com/Katana/katana/issues/562
                    formContent = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "client_credentials"), new kvp("scope", "scope1 scope2 scope3") });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken = JToken.Parse(responseMessage);
                    Assert.NotNull(jToken.SelectToken("access_token").Value<string>());
                    Assert.Equal<string>("bearer", jToken.SelectToken("token_type").Value<string>());
                    Assert.NotNull(jToken.SelectToken("expires_in").Value<string>());
                    Assert.Equal<string>("value1", jToken.SelectToken("param1").Value<string>());
                    Assert.Equal<string>("value2", jToken.SelectToken("param2").Value<string>());
                }
                finally
                {
                    //Finally close the client endpoint
                    if (clientEndpoint != null)
                    {
                        clientEndpoint.Dispose();
                    }
                }
            }
        }
        private static Guid GetShipmentKey(IHttpRouteData routeData, Uri requestUri) {

            // We are sure at this point that the shipmentKey value has been
            // supplied (either through route or quesry string) because it 
            // wouldn't be possible for the request to arrive here if it wasn't.
            object shipmentKeyString;
            if (routeData.Values.TryGetValue("shipmentKey", out shipmentKeyString)) {

                return Guid.ParseExact(shipmentKeyString.ToString(), "D");
            }

            // It's now sure that query string has the shipmentKey value
            var quesryString = requestUri.ParseQueryString();
            return Guid.ParseExact(quesryString["shipmentKey"], "D");
        }
Esempio n. 26
0
        public static bool IsYouTubeUri(Uri uri, out string videoId)
        {
            videoId = null;
            if (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps)
            {
                /*
                 * TODO: add support for all of the following
                 * (or even more, see http://stackoverflow.com/questions/3392993/php-regex-to-get-youtube-video-id)
                 * youtube.com/v/{vidid}
                 * youtube.com/vi/{vidid}
                 * youtube.com/?v={vidid}
                 * youtube.com/?vi={vidid}
                 * youtube.com/watch?v={vidid}
                 * youtube.com/watch?vi={vidid}
                 * youtu.be/{vidid}
                 */
                if ((uri.Host == "www.youtube.com" || uri.Host == "youtube.com") && uri.AbsolutePath == "/watch")
                {
                    var nvc = uri.ParseQueryString();
                    videoId = nvc["v"];
                    return videoId != null;
                }
                else if (uri.Host == "youtu.be")
                {
                    videoId = uri.AbsolutePath.Substring(1);
                    return true;
                }
            }

            return false;
        }
Esempio n. 27
0
        public override void Load(Uri uri)
        {
            media = new LocationMedia(uri.AbsoluteUri);
            if (uri.Scheme == "dshow")
            {
                var nvc = uri.ParseQueryString();
                foreach (var key in nvc.AllKeys)
                {
                    media.AddOption(key + "=" + nvc[key]);
                }
            }

            media.StateChanged += OnMediaStateChange;

            bool doLoop = false;

            vlc.EncounteredError += (sender, args) =>
            {
                OnMediaFailed();
            };

            vlc.EndReached += (sender, args) =>
            {
                if (!loop)
                {
                    Stop();
                    OnPlaybackEnded();
                }
                else
                {
                    doLoop = true;
                }
            };

            vlc.Playing += (sender, args) =>
            {
                if (loop && doLoop)
                {
                    OnSeekStart();
                }
                doLoop = false;
            };

            vlc.Media = media;
        }
        /// <summary>
        ///     Login redirect are of the form https://host/?ec=30x&startURL=xyz
        /// </summary>
        /// <param name="uri"></param>
        /// <returns>null if this is not a login redirect and return the the value for startURL if this is a login redirect</returns>
        private string IsLoginRedirect(Uri uri)
        {
            if (uri != null
                && uri.IsAbsoluteUri
                && uri.AbsolutePath != null && uri.AbsolutePath == "/"
                && uri.Query != null)
            {
                Dictionary<string, string> qs = uri.ParseQueryString();
                if ((qs["ec"] == "301" || qs["ec"] == "302") && qs["startURL"] != null)
                {
                    return qs["startURL"];
                }
            }

            return null;
        }
 public void ParseUriTest()
 {
     var uri = new Uri("http://foo.com/bar?a=123");
     var parameters = uri.ParseQueryString();
     Assert.AreEqual(1, parameters.Count);
     Assert.AreEqual("123", parameters["a"]);
 }
 public void ParseUri_EmptyQueryStringTest()
 {
     var uri = new Uri("http://foo.com/bar?");
     var parameters = uri.ParseQueryString();
     Assert.AreEqual(0, parameters.Count);
 }