private static string ExtractAuthHeader(System.Net.Http.Headers.HttpRequestHeaders headers, string headerName) { string result = String.Empty; try { //Check header result = String.IsNullOrEmpty(headers.GetValues(headerName).FirstOrDefault()) ? String.Empty : headers.GetValues(headerName).FirstOrDefault(); } catch (Exception) { //Nothing, the header was not found } if (String.IsNullOrEmpty(result)) { try { //Check Cookie var cookieAuth = GetCookie(headers, headerName); if (cookieAuth != null) { result = cookieAuth; } } catch { // fallback here because it is null } } return(result); }
public static string GetCookie(HttpRequestHeaders headers, string name) { var cookies = headers.GetCookies(name).FirstOrDefault(); if (cookies == null) return null; var cookie = cookies.Cookies.SingleOrDefault(x => x.Name == name); return cookie == null ? null : cookie.Value; }
public void SetUp() { var request = new HttpRequestMessage(); theHeaders = request.Headers; theKeyValues = new HeaderKeyValues(theHeaders); }
internal static void CopyTo(this HttpRequestHeaders from, HttpRequestHeaders to) { foreach (var header in from) { to.TryAddWithoutValidation(header.Key, header.Value); } }
internal void Populate(HttpRequestHeaders headers) { if (this.CacheControl != null) { headers.Add("response-cache-control", this.CacheControl); } if (this.ContentDisposition != null) { headers.Add("response-content-disposition", this.ContentDisposition); } if (this.ContentEncoding != null) { headers.Add("response-content-encoding", this.ContentEncoding); } if (this.ContentLanguage != null) { headers.Add("response-content-language", this.ContentLanguage); } if (this.ContentType != null) { headers.Add("response-content-type", this.ContentType); } if (this.Expires != null) { headers.Add("response-expires", this.Expires); } }
public static ApiCredentials GetFromRequestHeaders(HttpRequestHeaders requestHeaders) { //this could/should be another interface for testing purposes var authenticationHeader = requestHeaders.Authorization; if (authenticationHeader.Scheme != Configuration.AuthenticationScheme) { return null; } if (requestHeaders.Authorization == null || requestHeaders.Authorization.Parameter == null || !requestHeaders.Authorization.Parameter.Contains(":")) { return null; } var apiKey = requestHeaders.Authorization.Parameter.Split(':')[0]; if (apiKey == null) { return null; } var decodedBytes = Convert.FromBase64String(authenticationHeader.Parameter); var signature = Encoding.UTF8.GetString(decodedBytes); return new ApiCredentials() { Signature = signature, ApiKey = apiKey }; }
internal static string CanonicalizedHeaders(HttpRequestHeaders headers) { var canonicalizedString = new CanonicalizedString(string.Empty); var keyList = headers.Where(h => h.Key.StartsWith("x-ms-", StringComparison.OrdinalIgnoreCase)).Select(header => header.Key).ToList(); keyList.Sort(); foreach (string str2 in keyList) { var builder = new StringBuilder(str2); string str3 = ":"; foreach (string str4 in GetHeaderValues(headers, str2)) { string str5 = str4.Replace("\r\n", string.Empty); builder.Append(str3); builder.Append(str5); str3 = ","; } canonicalizedString.AppendCanonicalizedElement(builder.ToString()); } return canonicalizedString.Value.TrimEnd('\n').TrimStart('\n'); }
private string _GetCanonicalizedHeaders(HttpRequestHeaders headers) { var orderedHeaders = headers.OrderBy(x => x.Key); var headersWithAggregatedValues = orderedHeaders.Where(x => x.Key.StartsWith("x-ms")).Select(x => x.Key.ToLowerInvariant() + ":" + headers.GetValues(x.Key).Aggregate((x1, x2) => x1 + "," + x2)); var canonicalHeader = headersWithAggregatedValues.Aggregate((x1, x2) => x1 + "\n" + x2) + "\n"; return canonicalHeader; }
/// <summary> /// Authorization request header from client. /// </summary> /// <param name="header">header from client</param> /// <returns>-401/-403/{userId}</returns> public static long Authentication(HttpRequestHeaders header) { string authorization = header.GetValues("Authorization").FirstOrDefault(); if (authorization == null) { return -401; } using (var db = new CF_FamsamEntities()) { string token = authorization.Split(null)[1]; Session session = db.Session.Find(token); Debug.WriteLine("____________________________" + session.token); if (session == null) return -403; if (session.expired < DateTime.Now) { Debug.WriteLine("____________________________ session mili:" + session.expired.Millisecond); Debug.WriteLine("____________________________ now mili:" + DateTime.Now.Millisecond); //session expired db.Session.Remove(session); db.SaveChanges(); return -403; } else { return session.User.id; } } }
private async Task<ClaimsPrincipal> BuildClaimsPrincipal(HttpRequestHeaders headers) { string credentials; try { var token = Convert.FromBase64String(headers.Authorization.Parameter); credentials = Encoding.UTF8.GetString(token); } catch (FormatException) { return null; } catch (ArgumentException) { return null; } var parts = credentials.Split(':'); if (parts.Length != 2) return null; var userId = parts[0].Trim(); var password = parts[1].Trim(); if (! await _validateCredentials(userId, password)) return null; var claims = new[] {new Claim(ClaimTypes.Name, userId)}; var claimsIdentities = new[] {new ClaimsIdentity(claims, Scheme)}; return new ClaimsPrincipal(claimsIdentities); }
internal void Populate(HttpRequestHeaders headers) { if (this.Range != null) { headers.Range = new RangeHeaderValue(this.Range[0], this.Range[1]); } if (this.ModifiedSinceConstraint.HasValue) { headers.IfModifiedSince = new DateTimeOffset(this.ModifiedSinceConstraint.Value); } if (this.UnmodifiedSinceConstraint.HasValue) { headers.IfUnmodifiedSince = new DateTimeOffset(this.UnmodifiedSinceConstraint.Value); } if (this._matchingETagConstraints.Count > 0) { foreach (string temp in this._matchingETagConstraints) headers.IfMatch.Add(new EntityTagHeaderValue(temp)); } if (this._nonmatchingEtagConstraints.Count > 0) { foreach (string temp in this._nonmatchingEtagConstraints) headers.IfMatch.Add(new EntityTagHeaderValue(temp)); } }
/// <summary> /// Initializes a new instance of the <see cref="HttpRequestMessage" /> class /// with an HTTP method and a request System.Uri. /// </summary> /// <param name="method">The HTTP method.</param> /// <param name="requestUri">The System.Uri to request.</param> public HttpRequestMessage(HttpMethod method, Uri requestUri) { RequestUri = requestUri; Properties = new Dictionary<string, object>(); Version = new Version("1.1"); Method = method; Headers = new HttpRequestHeaders(new WebHeaderCollection()); }
public string Build(string verb, string content, StorageUri uri, AzureStorageAccountInfo accountInfo, HttpRequestHeaders headers, string contentType) { var ifMatch = ""; var md5 = ""; var canonicalizedHeaderString = _GetCanonicalizedHeaders(headers); var canonResource = _GetCanonicalizedResource(new Uri(uri.ToUriString()), accountInfo.Account); var authorizationHeader = _GetAuthorizationHeader(verb, content, ifMatch, canonicalizedHeaderString, canonResource, md5, accountInfo, contentType); return authorizationHeader; }
public static bool AuthenticateUser(HttpRequestHeaders HttpHeaders) { if (HttpHeaders.Contains(HttpRequestHeaderName)) { var authHeader = HttpHeaders.GetValues(HttpRequestHeaderName).First(); return _authenticateHeaderValue(authHeader); } return false; }
public static bool IsHeaderContainToken(HttpRequestHeaders header) { if (header.Contains(Constants.AccessTokenKey)) { return true; } return false; }
public string GetValueStorage(HttpRequestHeaders context, string key) { var cookie = context.GetCookies(key).FirstOrDefault(); if (cookie != null) return cookie[key].Value; return null; }
protected bool ReadAuthenticationContent(HttpRequestHeaders authenticationContent, string key, out string value) { value = string.Empty; var content = authenticationContent.FirstOrDefault(pair => pair.Key == key); if (content.Value == null || content.Value.Count() != 1) return false; value = content.Value.First(); return true; }
/// <summary> /// Canonicalizes the HTTP headers. /// </summary> /// <param name="method">The HTTP method for the request.</param> /// <param name="requestHeaders">The request headers.</param> /// <param name="contentHeaders">The content headers.</param> /// <returns>A string representation of the HTTP headers.</returns> private static string CanonicalizeHttpHeaders( HttpMethod method, HttpRequestHeaders requestHeaders, HttpContentHeaders contentHeaders) { long? contentLength = contentHeaders != null ? contentHeaders.ContentLength : null; return CanonicalizeHttpHeaders(method, contentLength, requestHeaders, contentHeaders); }
private static string GetCookieValue(IAbpAntiForgeryManager manager, HttpRequestHeaders headers) { var cookie = headers.GetCookies(manager.Configuration.TokenCookieName).LastOrDefault(); if (cookie == null) { return null; } return cookie[manager.Configuration.TokenCookieName].Value; }
public static void CopyTo(this HttpRequestHeaders fromHeaders, HttpRequestHeaders toHeaders) { Contract.Assert(fromHeaders != null, "fromHeaders cannot be null."); Contract.Assert(toHeaders != null, "toHeaders cannot be null."); foreach (KeyValuePair<string, IEnumerable<string>> header in fromHeaders) { toHeaders.TryAddWithoutValidation(header.Key, header.Value); } }
public static string GetHeaderValue(HttpRequestHeaders headers, string key) { IEnumerable<string> values; if (headers.TryGetValues(key, out values)) { return values.FirstOrDefault(); } return null; }
private static IEnumerable<string> GetHeaderValues(HttpRequestHeaders headers, string headerName) { var header = headers.Where( fx => fx.Key.Equals(headerName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); if ( header.Key != null && header.Value != null ) { return header.Value; } return new List<string>(); }
private static string GetHeaderValue(HttpRequestHeaders headers, string headerName) { var values = GetHeaderValues(headers, headerName); if (values.Any()) { // TODO: Test this to make sure it works in all cases, like null value of header key that exists return values.Take(1).FirstOrDefault(); } return string.Empty; }
public static UserDataPrincipal InitFromAuthCookie(HttpRequestHeaders headers) { string authCookieName = FormsAuthentication.FormsCookieName; var cookieValues = headers.GetCookies(authCookieName); CookieHeaderValue authCookieValue = cookieValues.FirstOrDefault(); if (authCookieValue == null) return null; CookieState authCookie = authCookieValue[authCookieName]; return DecryptAuthTicket(authCookie.Value); }
private void PopulateHeaders(HttpRequestHeaders httpRequestHeaders) { if (httpRequestHeaders.CacheControl != null) Headers.Add(new KeyValuePair("Cache-Control", httpRequestHeaders.CacheControl.ToString())); Headers.Add(new KeyValuePair("Connection", httpRequestHeaders.Connection.ToString())); Headers.Add(new KeyValuePair("Accept-Charset", httpRequestHeaders.AcceptCharset.ToString())); Headers.Add(new KeyValuePair("Accept-Encoding", httpRequestHeaders.AcceptEncoding.ToString())); Headers.Add(new KeyValuePair("Accept-Language", httpRequestHeaders.AcceptLanguage.ToString())); Headers.Add(new KeyValuePair("Host", httpRequestHeaders.Host.ToString())); Headers.Add(new KeyValuePair("User-Agent", httpRequestHeaders.UserAgent.ToString())); }
/// <summary> /// Resets the headers to make any request to the Nexon Api look legit /// </summary> /// <param name="headers">The <see cref="HttpRequestHeaderCollection" /> that gets modified</param> private static void SetHeaders(HttpRequestHeaders headers) { headers.Clear(); headers.Accept.ParseAdd("application/json, text/javascript, */*; q=0.01"); headers.AcceptEncoding.ParseAdd("gzip,deflate"); headers.AcceptLanguage.ParseAdd("en-GB,en-us;q=0.8,en;q=0.6"); headers.UserAgent.ParseAdd(GetUserAgent); headers.Connection.TryParseAdd("keep-alive"); headers.Host = new Uri(LoginUrl).Host; headers.Add("X-Requested-With", "XMLHttpRequest"); }
public ActionRequestEntry( HttpActionContext actionContext) { _controller = actionContext.ControllerContext.ControllerDescriptor.ControllerName; _action = actionContext.ActionDescriptor.ActionName; _arguments = actionContext.ActionArguments; _requestUri = actionContext.Request.RequestUri; _requestMethod = actionContext.Request.Method.Method; _requestHeaders = actionContext.Request.Headers; _clientIP = actionContext.Request.GetClientIpAddress(); }
private static IEnumerable<CookieHeaderValue> GetCookies(HttpRequestHeaders header) { var result = new System.Collections.ObjectModel.Collection<CookieHeaderValue>(); IEnumerable<string> cookies; if (header.TryGetValues("Cookie", out cookies)) { foreach (string cookie in cookies) { CookieHeaderValue cookieHeaderValue; if (CookieHeaderValue.TryParse(cookie, out cookieHeaderValue)) result.Add(cookieHeaderValue); } } return result; }
public static bool IsValid(this IAbpAntiForgeryManager manager, HttpRequestHeaders headers) { var cookieTokenValue = GetCookieValue(manager, headers); if (cookieTokenValue.IsNullOrEmpty()) { return true; } var headerTokenValue = GetHeaderValue(manager, headers); if (headerTokenValue.IsNullOrEmpty()) { return false; } return manager.As<IAbpAntiForgeryValidator>().IsValid(cookieTokenValue, headerTokenValue); }
private static string GetHeaderValue(IAbpAntiForgeryManager manager, HttpRequestHeaders headers) { IEnumerable<string> headerValues; if (!headers.TryGetValues(manager.Configuration.TokenHeaderName, out headerValues)) { return null; } var headersArray = headerValues.ToArray(); if (!headersArray.Any()) { return null; } return headersArray.Last().Split(", ").Last(); }
public static bool ExtractHeader( HttpRequestHeaders headers, string headerName, out string headerValue) { var token = headers.FirstOrDefault(x => x.Key == headerName); if (token.Key != null) { var firstToken = token.Value.FirstOrDefault(); if (firstToken != null) { headerValue = firstToken; return true; }; } headerValue = string.Empty; return false; }
public T GetResult <T>(PublicApiCall call, string requestData) where T : IResponse, new() { var s = string.Format("{0}/Api/{1}{2}", BaseUrl, call, requestData); System.Net.Http.Headers.HttpRequestHeaders h = _client.DefaultRequestHeaders; var response = _client.GetStringAsync(s); if (string.IsNullOrEmpty(response.Result)) { return(new T() { Success = false, Error = "No Response." }); } return(GetObject <T>(response.Result)); }
public static IEnumerable <KeyValuePair <string, string> > ParseToSingleValueKeyValuePairs(this HttpRequestHeaders headers) { return(headers.Select(x => new KeyValuePair <string, string>( x.Key, x.Value.FirstOrDefault()))); }