public static RaygunRequestMessage Build(HttpRequestMessage request, RaygunRequestMessageOptions options)
        {
            var message = new RaygunRequestMessage();

              options = options ?? new RaygunRequestMessageOptions();

              message.HostName = request.RequestUri.Host;
              message.Url = request.RequestUri.AbsolutePath;
              message.HttpMethod = request.Method.ToString();
              message.IPAddress = GetIPAddress(request);
              message.Form = ToDictionary(request.GetQueryNameValuePairs(), options.IsFormFieldIgnored);
              message.QueryString = ToDictionary(request.GetQueryNameValuePairs(), s => false);

              SetHeaders(message, request, options.IsHeaderIgnored);

              if (!options.IsRawDataIgnored)
              {
            string contentType = null;
            if (message.Headers != null && message.Headers.Contains("Content-Type"))
            {
              contentType = (string)message.Headers["Content-Type"];
            }

            if (contentType == null || CultureInfo.InvariantCulture.CompareInfo.IndexOf(contentType, "application/x-www-form-urlencoded", CompareOptions.IgnoreCase) < 0)
            {
              object body;
              if (request.Properties.TryGetValue(RaygunWebApiDelegatingHandler.RequestBodyKey, out body))
              {
            message.RawData = body.ToString();
              }
            }
              }

              return message;
        }
        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request.Headers.Authorization != null)
            {
                if (string.Equals(request.Headers.Authorization.Scheme, AuthenticationType, StringComparison.InvariantCultureIgnoreCase))
                {
                    string authToken = request.Headers.Authorization.Parameter;

                    // validate Token here
                    HandleAuthData(request, authToken);
                }
            } else // try query string parameters to find token
            {
                var authTokenFound = request.GetQueryNameValuePairs()
                    .Any(k => k.Key == QueryStringAuthHolderKey);

                if (authTokenFound)
                {
                    var tokenKvp = request.GetQueryNameValuePairs()
                        .First(k => k.Key == QueryStringAuthHolderKey);

                    HandleAuthData(request, tokenKvp.Value);
                }
            }

            var innerResult = await base.SendAsync(request, cancellationToken);

            return innerResult;
        }
 /// <summary>
 /// The parseQueryStringParameters method parses the string and sets some fields according to the result
 /// </summary>
 /// <param name="request">The request parameter</param>
 /// <param name="controller">The controller parameter</param>        
 private void ParseQueryStringParameters(HttpRequestMessage request, AnetApiController controller)
 {
     var queryStringPairs = request.GetQueryNameValuePairs();
     
     foreach (var pair in queryStringPairs)
     {
         switch (pair.Key)
         {
             case Constants.QueryParameters.Fields:
                 this.ParseDataShapingParameters(controller, pair); 
                 break;
             case Constants.QueryParameters.Offset:
                 this.ParsePageParameters(controller, pair); 
                 break;
             case Constants.QueryParameters.Limit:
                 this.ParsePageParameters(controller, pair); 
                 break;
             case Constants.QueryParameters.PageSize:
                 this.ParsePageParameters(controller, pair); 
                 break;
             case Constants.QueryParameters.PageNumber:
                 this.ParsePageParameters(controller, pair); 
                 break;
             case Constants.QueryParameters.SortKey:
                 this.ParseSortParameters(controller, pair); 
                 break;
             case Constants.QueryParameters.SortOrder:
                 this.ParseSortParameters(controller, pair); 
                 break;
             case Constants.QueryParameters.Filter:
                 this.ParseFilterParameters(controller, pair); 
                 break;
         }
     }
 }
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var response = await base.SendAsync(request, cancellationToken);
            if(!response.IsSuccessStatusCode)
            {
                // There was an error earlier in the pipeline so we just return the result as normal
                return response;
            }

            var content = response.Content as ObjectContent;
            if (content == null || content.Value == null)
            {
                // There is no object model for us to manipulate so there is nothing we can do.
                return response;
            }

            var requestedFields = _queryStringParser.GetRequestedFields(request.GetQueryNameValuePairs());
            if(!requestedFields.Any())
            {
                // The client has not specified any fields so just return the entire response to them as normal.
                return response;
            }

            var model = CreateDynamicObject(content.Value);
            FilterFields(model, requestedFields);

            var filteredResponse = request.CreateResponse(model);
            foreach (var header in response.Headers)
            {
                filteredResponse.Headers.Add(header.Key, header.Value);
            }

            return filteredResponse;
        }
 private static string GetApiKeyFromQueryString(HttpRequestMessage request)
 {
     return request.GetQueryNameValuePairs()
         .Where(pair => pair.Key == "apikey")
         .Select(pair => pair.Value)
         .FirstOrDefault();
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="ODataQueryOptions"/> class based on the incoming request and some metadata information from 
        /// the <see cref="ODataQueryContext"/>.
        /// </summary>
        /// <param name="context">The <see cref="ODataQueryContext"/> which contains the <see cref="IEdmModel"/> and some type information</param>
        /// <param name="request">The incoming request message</param>
        public ODataQueryOptions(ODataQueryContext context, HttpRequestMessage request)
        {
            if (context == null)
            {
                throw Error.ArgumentNull("context");
            }

            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            // remember the context
            Context = context;

            // Parse the query from request Uri
            RawValues = new ODataRawQueryOptions();
            IEnumerable<KeyValuePair<string, string>> queryParameters = request.GetQueryNameValuePairs();
            foreach (KeyValuePair<string, string> kvp in queryParameters)
            {
                switch (kvp.Key)
                {
                    case "$filter":
                        RawValues.Filter = kvp.Value;
                        ThrowIfEmpty(kvp.Value, "$filter");
                        Filter = new FilterQueryOption(kvp.Value, context);
                        break;
                    case "$orderby":
                        RawValues.OrderBy = kvp.Value;
                        ThrowIfEmpty(kvp.Value, "$orderby");
                        OrderBy = new OrderByQueryOption(kvp.Value, context);
                        break;
                    case "$top":
                        RawValues.Top = kvp.Value;
                        ThrowIfEmpty(kvp.Value, "$top");
                        Top = new TopQueryOption(kvp.Value, context);
                        break;
                    case "$skip":
                        RawValues.Skip = kvp.Value;
                        ThrowIfEmpty(kvp.Value, "$skip");
                        Skip = new SkipQueryOption(kvp.Value, context);
                        break;
                    case "$select":
                        RawValues.Select = kvp.Value;
                        break;
                    case "$inlinecount":
                        RawValues.InlineCount = kvp.Value;
                        break;
                    case "$expand":
                        RawValues.Expand = kvp.Value;
                        break;
                    case "$skiptoken":
                        RawValues.SkipToken = kvp.Value;
                        break;
                    default:
                        // we don't throw if we can't recognize the query
                        break;
                }
            }
        }
        public override bool Match(
            HttpRequestMessage request,
            IHttpRoute route,
            string parameterName,
            IDictionary<string, object> values,
            HttpRouteDirection routeDirection)
        {
            foreach (string key in HeaderConstraints.Keys)
            {
                if (!request.Headers.Contains(key)
                    || string.Compare(request.Headers.GetValues(key).FirstOrDefault(), HeaderConstraints[key].ToString(), true) != 0)
                {
                    return false;
                }
            }

            var queries = request.GetQueryNameValuePairs().ToDictionary(p => p.Key, p => p.Value);
            foreach (var key in QueryStringConstraints.Keys)
            {
                if (!queries.ContainsKey(key)
                    || string.Compare(queries[key], QueryStringConstraints[key].ToString(), true) != 0)
                {
                    return false;
                }
            }

            return base.Match(request, route, parameterName, values, routeDirection);
        }
        public async Task<FlowRequest> ReadGetAsync(HttpRequestMessage request)
        {
            Dictionary<string, string> dictionary = request.GetQueryNameValuePairs()
                .ToDictionary(x => x.Key, x => x.Value);

            return Create(dictionary);
        }
 public string[] ExtractSortExpressions(HttpRequestMessage requestMessage)
 {
     var queryParams = requestMessage.GetQueryNameValuePairs();
     var sortParam = queryParams.FirstOrDefault(kvp => kvp.Key == SortQueryParamKey);
     if (sortParam.Key != SortQueryParamKey) return new string[] {};
     return sortParam.Value.Split(',');
 }
        /// <summary>
        /// Add OAuth 1.0 Authorization Header to the request 
        /// </summary>
        public override async Task AddOAuthHeader(HttpRequestMessage request)
        {
            // Try to get token result from request. If not found make call to Gateway to get the token.
            if (!this.TryGetTokenResultFromHeader(out tokenResult))
            {
                this.tokenResult = await this.GetTokenResultAsync();
            }

            if(this.tokenResult == null || this.tokenResult.Properties == null)
            {
                Logger.LogError(request, false, "Token result or properties returned are null");
                throw new UnauthorizedAccessException(CommonResource.AccessTokenNotFound);
            }

            if (!this.tokenResult.Properties.ContainsKey("AccessToken"))
            {
                Logger.LogError(request, false, "Couldn't find AccessToken in OAuth TokenResult.");
                throw new UnauthorizedAccessException(CommonResource.AccessTokenNotFound);
            }

            if (!this.tokenResult.Properties.ContainsKey("ConsumerKey"))
            {
                Logger.LogError(request, false, "Couldn't find ConsumerKey in OAuth TokenResult.");
                throw new UnauthorizedAccessException(CommonResource.AccessTokenInvalid);
            }

            if (!this.tokenResult.Properties.ContainsKey("AccessTokenSecret"))
            {
                Logger.LogError(request, false, "Couldn't find AccessTokenSecret in OAuth TokenResult.");
                throw new UnauthorizedAccessException(CommonResource.AccessTokenInvalid);
            }

            Dictionary<string, string> arguments = new Dictionary<string, string>();
            foreach (KeyValuePair<string, string> pair in request.GetQueryNameValuePairs())
            {
                if (!string.IsNullOrEmpty(pair.Value))
                {
                    arguments.Add(pair.Key, pair.Value);
                }
            }

            Uri baseUrl = new Uri(request.RequestUri.GetLeftPart(UriPartial.Path));

            string nonce = GenerateNonce();
            string timestamp = GenerateTimestamp();
            string signature = await this.GenerateSignature(request.Method, baseUrl, nonce, timestamp, arguments);

            string authHeader = string.Format(CultureInfo.InvariantCulture,
                                            AuthHeaderFormatOAuth1,
                                            Uri.EscapeDataString(this.tokenResult.Properties["AccessToken"]),
                                            Uri.EscapeDataString(nonce),
                                            Uri.EscapeDataString(this.tokenResult.Properties["ConsumerKey"]),
                                            Uri.EscapeDataString(HashAlgorithm),
                                            Uri.EscapeDataString(timestamp),
                                            Uri.EscapeDataString(Version),
                                            Uri.EscapeDataString(signature));

            request.Headers.Add(AuthorizationHeader, authHeader);
        }
 private static string GetQueryValue(HttpRequestMessage request)
 {
     var pair = request.GetQueryNameValuePairs()
         .FirstOrDefault(kvp => kvp.Key.ToUpperInvariant().Equals(PartialResponseQueryParameterKey));
     return object.Equals(pair, default(System.Collections.Generic.KeyValuePair<string,string>))
         ? null
         : pair.Value;
 }
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, 
            CancellationToken cancellationToken)
        {
            // the fall back language
            var langauges = new List<StringWithQualityHeaderValue>();

            // Check the AcceptLanguage simulated header in the query string first. This will ignore lettercase.
            NameValueCollection query = request.GetQueryNameValuePairs()
                .Aggregate(new NameValueCollection(), (col, kvp) =>
                {
                    col.Add(kvp.Key, kvp.Value);
                    return col;
                });

            if (query[FallbackHeaderConstants.AcceptLanguage] != null)
            {
                langauges.Add(new StringWithQualityHeaderValue(query[FallbackHeaderConstants.AcceptLanguage], 1.0));
            }
            else if (request.Headers.AcceptLanguage != null)
            {
                // then check the Accept-Language header.
                langauges.AddRange(request.Headers.AcceptLanguage);
            }

            langauges = langauges.OrderByDescending(l => l.Quality).ToList();

            // this is the final fall-back culture.
            var culture = CultureInfo.DefaultThreadCurrentCulture;
            var uiCulture = CultureInfo.DefaultThreadCurrentUICulture;

            // try to break and find one language that's available
            foreach (StringWithQualityHeaderValue lang in langauges)
            {
                try
                {
                    culture = CultureInfo.GetCultureInfo(lang.Value);
                    uiCulture = culture;
                    break;
                }
                catch (CultureNotFoundException)
                {
                    // ignore the error
                }
            }

            if (_setThreadCulture)
            {
                Thread.CurrentThread.CurrentCulture = culture ?? _lastResortFallback;
            }
            if (_setThreadUiCulture)
            {
                Thread.CurrentThread.CurrentUICulture = uiCulture ?? _lastResortFallback;
            }

            return base.SendAsync(request, cancellationToken);
        }
        public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
        {
            var pairs = request.GetQueryNameValuePairs();
            if (pairs.Any(p => p.Key == "envelope" && p.Value == "false"))
            {
                return jsonMediaTypeFormatter;
            }

            return envelopeJsonMediaTypeFormatter;
        }
        private void from_url(HttpRequestMessage request)
        {
            var items =
                        request.GetQueryNameValuePairs().Where(q => q.Key == "connection_id").ToList();

            if (items.Any())
            {
                update_last_seen(items.First().Value);
            }
        }
        private static string VersionFromApiKey(HttpRequestMessage request)
        {
            foreach (var param in request.GetQueryNameValuePairs())
            {
                if (param.Key.ToLower() == "api_key")
                    return param.Value;
            }

            return "2.0";
        }
    public HttpRequestDetails(HttpRequestMessage message, RaygunRequestMessageOptions options = null)
    {
      options = options ?? new RaygunRequestMessageOptions();

      RequestUri = message.RequestUri;
      Method = message.Method;
      Form = ToDictionary(message.GetQueryNameValuePairs(), options.IsFormFieldIgnored);
      IPAddress = GetIPAddress(message);
      SetHeadersAndRawData(message, options.IsHeaderIgnored);
    }
 private NameValueCollection ParseQueryString(Uri uri)
 {
     HttpRequestMessage request = new HttpRequestMessage { RequestUri = uri };
     NameValueCollection nameValuePairs = new NameValueCollection();
     foreach (KeyValuePair<string, string> keyValuePair in request.GetQueryNameValuePairs())
     {
         nameValuePairs.Add(keyValuePair.Key, keyValuePair.Value);
     }
     return nameValuePairs;
 }
        private static string GetPassword(HttpRequestMessage request)
        {
            IEnumerable<string> values;
            if (request.Headers.TryGetValues("password", out values))
                return values.FirstOrDefault();

            return request.GetQueryNameValuePairs().Where(
                kv => string.Equals(kv.Key, "password", StringComparison.OrdinalIgnoreCase))
                .Select(kv => kv.Value).FirstOrDefault();
        }
Exemple #19
0
        public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, System.Net.Http.HttpRequestMessage request, System.Net.Http.Headers.MediaTypeHeaderValue mediaType)
        {
            string callback;

            if (request.GetQueryNameValuePairs().ToDictionary(pari => pari.Key, pari => pari.Value).TryGetValue("callback", out callback))
            {
                return(new JsonpMediaTypeFormatter(callback));
            }
            return(this);
        }
        private bool IgnoreCache(HttpRequestMessage request)
        {
            var result = false;
            var parms = request.GetQueryNameValuePairs().ToDictionary(x => x.Key.ToLower(), x => x.Value);
            if (parms.ContainsKey("ignorecache"))
            {
                Boolean.TryParse(parms["ignorecache"], out result);
            }

            return result;
        }
Exemple #21
0
        public static string GetQueryString(HttpRequestMessage request, string key)
        {
            var queryStrings = request.GetQueryNameValuePairs();
            if (queryStrings == null)
                return null;

            var match = queryStrings.FirstOrDefault(kv => string.Compare(kv.Key, key, true) == 0);
            if (string.IsNullOrEmpty(match.Value))
                return null;

            return match.Value;
        }
        public HttpResponseMessage Companies(HttpRequestMessage request)
        {
            var service = new ODataService();
            var result = service.Execute(Company.GetCompanies(), request.GetQueryNameValuePairs());

            var response = request.CreateResponse();
            response.Content = new StringContent(result.Results.ToString(), Encoding.UTF8, "application/json");
            return response;

            // alternatively, we could change the return type to object and do:
            // return JObject.Parse(result.Results.ToString());
            // this is necessary (for now) since WebApi wants to be the one to do the serialization
        }
 bool IHttpRouteConstraint.Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
 {
     var queries = request.GetQueryNameValuePairs().ToDictionary(p => p.Key, p => p.Value);
     foreach (var key in QueryStringConstraints.Keys)
     {
         if (!queries.ContainsKey(key)
             || string.Compare(queries[key], QueryStringConstraints[key].ToString(), true, CultureInfo.CurrentCulture) != 0)
         {
             return false;
         }
     }
     return true;
 }
        public RaygunWebApiRequestMessage(HttpRequestMessage request, RaygunRequestMessageOptions options = null)
        {
            options = options ?? new RaygunRequestMessageOptions();

              HostName = request.RequestUri.Host;
              Url = request.RequestUri.AbsolutePath;
              HttpMethod = request.Method.ToString();
              IPAddress = GetIPAddress(request);

              Form = ToDictionary(request.GetQueryNameValuePairs(), options.IsFormFieldIgnored);

              SetHeadersAndRawData(request, options.IsHeaderIgnored);
        }
 public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
 {
     if (request.Method != HttpMethod.Get)
     {
         return this;
     }
     string callback;
     if (request.GetQueryNameValuePairs().ToDictionary(pair => pair.Key, pair => pair.Value).TryGetValue("callback", out callback))
     {
         return new JsonpMediaTypeFormatter(callback);
     }
     return this;
 }
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            bool IsRequestCultureSet = false;
            bool IsRequestGlobalCultureSet = false;

			string locale = request.GetQueryNameValuePairs().SingleOrDefault(kvp => kvp.Key == "locale").Value;

			// try setting locale from query string
			if (_supportedLocales.Any(kvp => kvp.Key == locale))
			{
				SetCulture(request, _supportedLocales.FirstOrDefault(i => i.Key == locale).Value);
			}

			// try setting it from accept-language header
			else
			{
				foreach (var lang in request.Headers.AcceptLanguage)
				{
					if (_supportedLocales.Any(kvp => kvp.Key == lang.Value))
					{
						SetCulture(request, lang.Value);
						IsRequestCultureSet = true;
						break;
					}
				}

				if (!IsRequestCultureSet)
				{
					foreach (var lang in request.Headers.AcceptLanguage)
					{
						var globalLang = lang.Value.Substring(0, 2);
						if (_supportedLocales.Any(t => t.Key.StartsWith(globalLang)))
						{
							SetCulture(request, _supportedLocales.FirstOrDefault(i => i.Key.StartsWith(globalLang)).Value);
							IsRequestGlobalCultureSet = true;
							break;
						}
					}
				}

				if (!IsRequestGlobalCultureSet && !IsRequestCultureSet)
				{
					SetCulture(request, DEFAULT_CULTURE);
				}
			}

            var response = await base.SendAsync(request, cancellationToken);

            return response;
        }
        internal static AuthorizationLevel GetAuthorizationLevel(HttpRequestMessage request, SecretManager secretManager, string functionName = null)
        {
            // TODO: Add support for validating "EasyAuth" headers

            // first see if a key value is specified via headers or query string (header takes precidence)
            IEnumerable<string> values;
            string keyValue = null;
            if (request.Headers.TryGetValues(FunctionsKeyHeaderName, out values))
            {
                keyValue = values.FirstOrDefault();
            }
            else
            {
                var queryParameters = request.GetQueryNameValuePairs().ToDictionary(p => p.Key, p => p.Value, StringComparer.OrdinalIgnoreCase);
                queryParameters.TryGetValue("code", out keyValue);
            }

            if (!string.IsNullOrEmpty(keyValue))
            {
                // see if the key specified is the master key
                HostSecrets hostSecrets = secretManager.GetHostSecrets();
                if (!string.IsNullOrEmpty(hostSecrets.MasterKey) &&
                    SecretEqual(keyValue, hostSecrets.MasterKey))
                {
                    return AuthorizationLevel.Admin;
                }

                // see if the key specified matches the host function key
                if (!string.IsNullOrEmpty(hostSecrets.FunctionKey) &&
                    SecretEqual(keyValue, hostSecrets.FunctionKey))
                {
                    return AuthorizationLevel.Function;
                }

                // if there is a function specific key specified try to match against that
                if (functionName != null)
                {
                    FunctionSecrets functionSecrets = secretManager.GetFunctionSecrets(functionName);
                    if (functionSecrets != null &&
                        !string.IsNullOrEmpty(functionSecrets.Key) &&
                        SecretEqual(keyValue, functionSecrets.Key))
                    {
                        return AuthorizationLevel.Function;
                    }
                }
            }

            return AuthorizationLevel.Anonymous;
        }
        private string GetJsonpCallback(HttpRequestMessage request)
        {
            var callback = string.Empty;
            if (request.Method == HttpMethod.Get)
            {
                var query = request.GetQueryNameValuePairs();

                if (query != null)
                {
                    var queryVal = query.FirstOrDefault(x => x.Key.ToLower() == "callback");
                    if (!queryVal.Equals(default(KeyValuePair<string, string>))) callback = queryVal.Value;
                }
            }
            return callback;
        }
Exemple #29
0
        protected override bool Match(TestTarget target, HttpRequestMessage request)
        {
            _tags = _tags ?? (_tags = target.ResolveDependency(TestDefinition.TestType)
                                            .IfTypeIs<IHaveTags>()
                                            .Then(test =>
                                            {
                                                var tags = test.Tags;
                                                TestDefinition.Tags = tags;
                                                return tags;
                                            })
                                            .ElseDefault()
                                            .OrEmpty()
                                            .ToArray());

            return DoTestsMatchFilterRequest(_tags, request.GetQueryNameValuePairs().ToArray());
        }
        public JsonQueryOptions( HttpRequestMessage request)
        {
            if (request == null)
            {
                throw new Exception("request is null");
            }

            // remember the context and request
            Request = request;

            // Parse the query from request Uri
            RawValues = new RawQueryOptions();
            IEnumerable<KeyValuePair<string, string>> queryParameters = request.GetQueryNameValuePairs();
            foreach (KeyValuePair<string, string> kvp in queryParameters)
            {
                switch (kvp.Key)
                {
                    case "$where":
                        RawValues.Where = kvp.Value;
                        ThrowIfEmpty(kvp.Value, "$where");
                        Where = new FilterQueryOption(kvp.Value);
                        break;
                    case "$orderby":
                        RawValues.OrderBy = kvp.Value;
                        ThrowIfEmpty(kvp.Value, "$orderby");
                        OrderBy = new OrderByQueryOption(kvp.Value);
                        break;
                    case "$top":
                        RawValues.Top = kvp.Value;
                        ThrowIfEmpty(kvp.Value, "$top");
                        Top = new TopQueryOption(kvp.Value);
                        break;
                    case "$skip":
                        RawValues.Skip = kvp.Value;
                        ThrowIfEmpty(kvp.Value, "$skip");
                        Skip = new SkipQueryOption(kvp.Value, RawValues);
                        break;
                    case "$skiptoken":
                        RawValues.SkipToken = kvp.Value;
                        break;
                    default:
                        // we don't throw if we can't recognize the query
                        break;
                }
            }
        }
        public HttpResponseMessage Get(HttpRequestMessage request)
        {
            Tracing.Information("Simple HTTP endpoint called.");

            var query = request.GetQueryNameValuePairs();
            var auth = new AuthenticationHelper();

            var realm = query.FirstOrDefault(p => p.Key.Equals("realm", System.StringComparison.OrdinalIgnoreCase)).Value;
            var tokenType = query.FirstOrDefault(p => p.Key.Equals("tokenType", System.StringComparison.OrdinalIgnoreCase)).Value;

            if (string.IsNullOrWhiteSpace(realm))
            {
                return request.CreateErrorResponse(HttpStatusCode.BadRequest, "realm parameter is missing.");
            }

            EndpointReference appliesTo;
            try
            {
                appliesTo = new EndpointReference(realm);
                Tracing.Information("Simple HTTP endpoint called for realm: " + realm);
            }
            catch
            {
                Tracing.Error("Malformed realm: " + realm);
                return request.CreateErrorResponse(HttpStatusCode.BadRequest, "malformed realm name.");
            }

            if (string.IsNullOrWhiteSpace(tokenType))
            {
                tokenType = ConfigurationRepository.Global.DefaultHttpTokenType;
            }

            Tracing.Verbose("Token type: " + tokenType);

            TokenResponse tokenResponse;
            var sts = new STS();
            if (sts.TryIssueToken(appliesTo, ClaimsPrincipal.Current, tokenType, out tokenResponse))
            {
                var resp = request.CreateResponse<TokenResponse>(HttpStatusCode.OK, tokenResponse);
                return resp;
            }
            else
            {
                return request.CreateErrorResponse(HttpStatusCode.BadRequest, "invalid request.");
            }
        }
Exemple #32
0
        public static IDictionary <string, object> ToDictionaryIn(this System.Net.Http.HttpRequestMessage message)
        {
            Dictionary <string, object> d = new Dictionary <string, object>();

            d.Add("xf-request.message.uri", message.RequestUri.ToString());
            d.Add("xf-request.message.local-path", message.RequestUri.LocalPath.Trim(new char[] { '/' }).ToLower());
            d.Add("xf-request.message.http-method", message.Method.Method.ToUpper());


            if (message.Headers.Authorization != null)
            {
                d.Add("xf-request.message.auth-schema", message.Headers.Authorization.Scheme);
                d.Add("xf-request.message.auth-value", message.Headers.Authorization.Parameter);
                if (message.Headers.Authorization.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase))
                {
                    d.Add("xf-request.message.basic-token", message.Headers.Authorization.Parameter);
                }
                if (message.Headers.Authorization.Scheme.Equals("bearer", StringComparison.OrdinalIgnoreCase))
                {
                    d.Add("xf-request.message.bearer-token", message.Headers.Authorization.Parameter);
                }
            }
            else
            {
                d.Add("xf-request.message.auth-schema", "none");
                d.Add("xf-request.message.auth-value", "none");
            }
            d.Add("xf-request.message.protocol", message.RequestUri.Scheme.ToLower());

            string host = message.RequestUri.Host.ToLower();

            d.Add("xf-request.message.host", host.ToLower());
            var parts = host.Split(new char[] { '.' });

            if (parts.Length > 1)
            {
                d.Add("xf-request.message.sub-domain", parts[0].ToLower());
            }
            if (message.Properties.ContainsKey("MS_HttpContext"))
            {
                var context = ((System.Web.HttpContextWrapper)message.Properties["MS_HttpContext"]);
                if (!String.IsNullOrEmpty(context.Request.UserHostAddress))
                {
                    d.Add("xf-request.message.client-ip", context.Request.UserHostAddress);
                }
                if (!String.IsNullOrWhiteSpace(context.Request.UserAgent))
                {
                    d.Add("xf-request.message.user-agent", context.Request.UserAgent);
                }
            }

            foreach (var item in message.Headers)
            {
                d.Add(String.Format("xf-request.header.{0}", item.Key.ToLower()), item.Value);
            }

            foreach (var item in message.Properties)
            {
                if (item.Key.Equals("{8572540D-3BD9-46DA-B112-A1E6C9086003}", StringComparison.OrdinalIgnoreCase))
                {
                    QueryStringValueProvider provider = item.Value as QueryStringValueProvider;
                    if (provider != null)
                    {
                        foreach (var kvp in provider.GetKeysFromPrefix(""))
                        {
                            string key = kvp.Key;
                            ValueProviderResult vpr = (ValueProviderResult)provider.GetValue(key);
                            d.Add(String.Format("xf-request.query-string.{0}", key), vpr.AttemptedValue);
                        }
                    }
                }
            }

            foreach (KeyValuePair <string, string> kvp in message.GetQueryNameValuePairs())
            {
                string key = String.Format("xf-request.query-string.{0}", kvp.Key);
                d.Add(key, kvp.Value);
            }


            return(d);
        }
Exemple #33
0
 public static Dictionary <string, string> GetODataParams(this HttpRequestMessage request)
 {
     return(request.GetQueryNameValuePairs().Where(kvp => kvp.Key.StartsWith("$")).ToDictionary(kvp => kvp.Key, kvp => kvp.Value));
 }