public static bool IsTokenValid(string modulo, string accion, HttpRequestHeaders headers) { bool result = false; try { string token = headers.GetValues("token").FirstOrDefault(); if (token == null) { token = headers.GetValues("Token").FirstOrDefault(); } if (token == null) { return(result); } USUARIO = Util.DecryptToken(headers); if (USUARIO != null) { result = true; } } catch (Exception ex) { } return(result); }
/// <summary> /// Check if Token is Authenticated With User ID /// </summary> /// <returns></returns> private bool IsTokenAuthenticated() { HttpRequestHeaders headers = this.Request.Headers; string _headerToken = string.Empty; if (headers.Contains("header_token")) { _headerToken = headers.GetValues("header_token").First(); } if (headers.Contains("user_id")) { _userId = Convert.ToInt32(headers.GetValues("user_id").First()); } User_BLL _objUserBll = new User_BLL(); if (_headerToken == string.Empty || _userId == 0) { _strJSONContent.Append("{\"status\":\"UnAuthorized\"}"); return(false); } else if (!(_objUserBll.IsTokenAuthenticated(_headerToken, _userId))) { _strJSONContent.Append("{\"status\":\"UnAuthorized\"}"); return(false); } else { return(true); } }
/// <summary> /// Provides a representation of custom headers content, name of which are in another header /// </summary> /// <param name="headers"></param> /// <param name="customHeaderName"></param> /// <returns>Custom header values separated by \\n, otherwise string.Empty if no custom headers, null if any custom header is missing</returns> /// <remarks>If multiple values exist for a custom header they are joined with ", " since HttpClient will follow this policy and it also complies with RFC2616</remarks> public static string CustomHeadersRepresentation(this HttpRequestHeaders headers, string customHeaderName) { var customHeaders = headers.GetValues <string>(customHeaderName).FirstOrDefault(); if (string.IsNullOrEmpty(customHeaders)) { // No custom headers required, return empty, not null, to avoid failing the signature return(string.Empty); } var values = new List <string>(); foreach (var headerName in customHeaders.Split(' ')) { var hv = headers.GetValues <string>(headerName).ToList(); if (hv.Count == 0) { return(null); } // TODO: Do we need to iterate over to make sure we don't have empty/null values? var value = string.Join(", ", hv); values.Add(value); } var result = string.Join("\n", values); return(result); }
public static List <string> ReadUserPassHeader(HttpRequestHeaders header) { List <string> list = new List <string>(); string userName = string.Empty; string password = string.Empty; string userKarbord = string.Empty; if (header.Contains("userName")) { userName = header.GetValues("userName").First(); } if (header.Contains("password")) { password = header.GetValues("password").First(); } if (header.Contains("userKarbord")) { userKarbord = header.GetValues("userKarbord").First(); } list.Add(userName); list.Add(password); list.Add(userKarbord); return(list); }
/// <summary> /// 获取海康加密的headers /// </summary> /// <param name="headers"></param> /// <param name="method"></param> /// <returns></returns> private static Dictionary <string, string> GetHikSecurityHeaders(HttpRequestHeaders headers, string method, string url, Dictionary <string, string> formData) { method = method.ToUpperInvariant(); Dictionary <string, string> dic = new Dictionary <string, string> { { "method", method } }; if (headers.Contains("accept")) { dic.Add("accept", headers.GetValues("accept-header")?.FirstOrDefault()?.Trim() ?? ""); } if (headers.Any(o => o.Key.ToLower().Equals("content-type"))) { dic.Add("content-type", headers.GetValues("content-type")?.FirstOrDefault()?.Trim() ?? ""); } if (headers.Any(o => o.Key.ToLower().Equals("date"))) { dic.Add("date", headers.GetValues("date")?.FirstOrDefault()?.Trim() ?? ""); } if (headers.Any(o => o.Key.ToLower().Equals("headers"))) { dic.Add("headers", headers.GetValues("headers")?.FirstOrDefault()?.Trim() ?? ""); } dic.Add("url", BuildResource(url, headers, formData)); return(dic); }
public void Headers_Response() { HttpRequestMessage message = new HttpRequestMessage(); HttpRequestHeaders headers = message.Headers; headers.Add("Age", "vv"); Assert.AreEqual("vv", headers.GetValues("Age").First(), "#1"); headers.Clear(); headers.TryAddWithoutValidation("Age", "vv"); Assert.AreEqual("vv", headers.GetValues("Age").First(), "#2"); // .NET encloses the "Age: vv" with two whitespaces. var normalized = Regex.Replace(message.ToString(), @"\s", ""); #if !__WATCHOS__ if (HttpClientTestHelpers.UsingSocketsHandler) #endif Assert.AreEqual("Method:GET,RequestUri:'<null>',Version:2.0,Content:<null>,Headers:{Age:vv}", normalized, "#3"); #if !__WATCHOS__ else { Assert.AreEqual("Method:GET,RequestUri:'<null>',Version:1.1,Content:<null>,Headers:{Age:vv}", normalized, "#3"); } #endif }
private (int start, int?count) ParseGetAllHeaders(HttpRequestHeaders headers) { string startValue = headers.GetValues("start").FirstOrDefault() ?? "0"; string countValue = headers.GetValues("count").FirstOrDefault(); return(ParseHeaderValue(startValue), countValue != null ? ParseHeaderValue(countValue) : (int?)null); }
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { HttpRequestHeaders headers = context.Request.Headers; string requestGetApiKey = headers.GetValues("getApiKey").First(); string requestPostApiKey = headers.GetValues("postApiKey").First(); if (string.IsNullOrEmpty(requestPostApiKey) && string.IsNullOrEmpty(requestPostApiKey)) { } else { if (!string.IsNullOrEmpty(requestPostApiKey)) { } } //context.Request.Method.Method if (context.Request.Method.Method == "GET") { if (!GETAPIKEY.Equals(requestGetApiKey)) { HttpContext.Current.Response.Write("you are not authorized to access api.Please check api key"); context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request); } } if (context.Request.Method.Method == "POST") { if (!POSTAPIKEY.Equals(requestPostApiKey)) { HttpContext.Current.Response.Write("you are not authorized to access api.Please check api key"); context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request); } } return(Task.FromResult(0)); }
public async Task <IHttpActionResult> DeleteIngredient([FromBody] int id) { HttpRequestHeaders headers = this.Request.Headers; string app_key = string.Empty; if (headers.Contains("app_key")) { app_key = headers.GetValues("app_key").First(); } if (headers.Contains("id")) { id = int.Parse(headers.GetValues("id").First()); } AuthApp app = await db.AuthApps.Where(a => a.auth_key.Equals(app_key)).FirstAsync(); if (app == null) { return(NotFound()); } Ingredient ingredient = await db.Ingredients.FindAsync(id); if (ingredient == null) { return(NotFound()); } db.Ingredients.Remove(ingredient); await db.SaveChangesAsync(); return(Ok(ingredient)); }
/// <summary> /// Verifies the given request parts with the Signature class. /// </summary> /// <example> /// /// </example> /// <returns>Whether or not the </returns> /// <param name="request">An Http request that contins the various parts of the signed request.</param> public async Task <bool> VerifyAsync(HttpRequestMessage request) { HttpRequestHeaders headers = request.Headers; if (!headers.Contains(SIGNATURE_HEADER)) { throw new InvalidHeadersException($"The header {SIGNATURE_HEADER} is missing"); } string signatureHeader = headers.GetValues(SIGNATURE_HEADER).First(); Signature signature = new Signature(signatureHeader); if (!headers.Contains(SIGNED_HEADERS)) { throw new InvalidHeadersException($"The header {SIGNED_HEADERS} is missing"); } if (!headers.Contains(DATE_HEADER)) { throw new InvalidHeadersException($"The header {DATE_HEADER} is missing"); } if (!this.checker.VerifyDate(headers.GetValues(DATE_HEADER).First())) { throw new InvalidHeadersException($"The header {DATE_HEADER} is not within five minutes of the request"); } return(signature.Validate(this.publicKey, await this.CanonizeAsync(request))); }
public static string ValideLogined(HttpRequestHeaders heads) { if (heads.GetValues("token") == null || !heads.GetValues("token").Any()) { throw new Exception("请登录!"); } return(Decode(heads.GetValues("token").FirstOrDefault(), Key)[""].ToString()); }
/// <summary> /// 驗證是否有登入過 /// </summary> public static string ValideLogined(HttpRequestHeaders headers) { if (headers.GetValues("token").First() == null) { throw new Exception("請登入"); } return(Decode(headers.GetValues("token").First(), key)); }
public static string IsValieLogin(HttpRequestHeaders headers) { if (headers.GetValues("token") == null || !headers.GetValues("token").Any()) { throw new Exception("请登录"); } return(Decode(headers.GetValues("token").First(), JwtKeys)); }
public static string ValideLogined(HttpRequestHeaders headers) { if (headers.GetValues("token") == null || !headers.GetValues("token").Any()) { throw new Exception("未登录"); } var dic = Decode(secret, headers.GetValues("token").First()); return(dic["LoginName"].ToString()); }
public bool AdminLogged(HttpRequestHeaders header) { if (header.Contains("name") && header.Contains("password")) { var name = header.GetValues("name").First(); var password = header.GetValues("password").First(); return(adminLogic.Login(name, password)); } return(false); }
public static string AccessControlRequestHeaders(this HttpRequestHeaders headers) { if (headers.Contains(accessControlRequestHeadersKey) && headers.GetValues(accessControlRequestHeadersKey).Any()) { return(headers.GetValues(accessControlRequestHeadersKey).First()); } return(null); }
private void CheckHeaders(HttpRequestHeaders header) { var versionHeader = header.GetValues("X-Firebase-Client").First(); Assert.Equal(FirebaseMessagingClient.ClientVersion, versionHeader); var apiFormatHeader = header.GetValues("X-GOOG-API-FORMAT-VERSION").First(); Assert.Equal("2", apiFormatHeader); }
public static string Origin(this HttpRequestHeaders headers) { if (headers.Contains(originHeaderKey) && headers.GetValues(originHeaderKey).Any()) { return(headers.GetValues(originHeaderKey).First()); } return(null); }
public static string DecryptHeader(HttpRequestHeaders headers, string headerkey) { var value = headers.GetValues(headerkey).FirstOrDefault(); if (string.IsNullOrWhiteSpace(value)) { throw new WebApiException(ErrorList.UnableToProcess, System.Net.HttpStatusCode.PreconditionFailed); } return(headers.Contains("Decrypt") && headers.GetValues("Decrypt").First().Equals("false") ? value : EncryptionHelper.AesDecryption(value.Replace("%3D", "=").Replace("%3d", "="), EncryptionKey.LOG)); }
public static string GetUserFromHeaders(HttpRequestHeaders headers, bool useFake = false) { string usuario = ""; usuario = headers.GetValues("user").FirstOrDefault(); if (useFake && headers.Contains("personificado") && headers.GetValues("personificado").FirstOrDefault() != null) { usuario = headers.GetValues("personificado").FirstOrDefault(); } return(usuario); }
public void Headers_Response() { HttpRequestMessage message = new HttpRequestMessage(); HttpRequestHeaders headers = message.Headers; headers.Add("Age", "vv"); Assert.AreEqual("vv", headers.GetValues("Age").First(), "#1"); headers.Clear(); headers.AddWithoutValidation("Age", "vv"); Assert.AreEqual("vv", headers.GetValues("Age").First(), "#2"); Assert.AreEqual("Method: GET, RequestUri: '<null>', Version: 1.1, Content: <null>, Headers:\r\n{\r\nAge: vv\r\n}", message.ToString(), "#3"); }
private long ParseVersionHeader(HttpRequestHeaders headers) { long version; if (headers.Contains(VERSION_HEADER_NAME) && headers.GetValues(VERSION_HEADER_NAME).FirstOrDefault().Length > 0) { var hval = headers.GetValues(VERSION_HEADER_NAME).FirstOrDefault(); if (long.TryParse(hval, out version)) { return(version); } } return(-1); }
internal void VerifyActionExecuteHeaders(HttpVerb verb, HttpRequestHeaders headers, OperationParameter[] inputParameters) { if (verb == HttpVerb.Post && inputParameters.OfType <BodyOperationParameter>().Any()) { this.Assert.IsTrue(headers.GetValues(HttpHeaders.ContentType).Contains(MimeTypes.ApplicationJsonLight), string.Format("Unexpected Content-Type header value:{0}", headers.GetValues(HttpHeaders.ContentType))); } else { this.Assert.IsNull(headers.GetValues(HttpHeaders.ContentType), "Unexpected Content-Type header."); } this.Assert.IsNull(headers.GetValues(HttpHeaders.ContentLength), "Unexpected Content-Length header."); this.Assert.AreEqual("3.0;NetFx", headers.GetValues(HttpHeaders.MaxDataServiceVersion), "Unexpected MaxDataServiceVersion header value."); this.Assert.AreEqual(MimeTypes.ApplicationAtomXml + "," + MimeTypes.ApplicationXml, headers.GetValues(HttpHeaders.Accept), "Unexpected Accept header value."); }
public async Task <IHttpActionResult> PostIngredient([FromBody] Ingredient ingredient) { HttpRequestHeaders headers = this.Request.Headers; string app_key = string.Empty; if (headers.Contains("app_key")) { app_key = headers.GetValues("app_key").First(); } AuthApp app = await db.AuthApps.Where(a => a.auth_key.Equals(app_key)).FirstAsync(); if (app == null) { return(NotFound()); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } db.Ingredients.Add(ingredient); await db.SaveChangesAsync(); return(CreatedAtRoute("DefaultApi", new { id = ingredient.id }, ingredient)); }
public IHttpActionResult generaApuesta(Apuesta_Model datosApuesta) { Apuesta_Model respuesta = new Apuesta_Model(); if (datosApuesta != null) { HttpRequestHeaders headers = this.Request.Headers; string idUsuario = string.Empty; if (headers.Contains("Id_Usuario")) { idUsuario = headers.GetValues("Id_Usuario").First(); } if (!new Apuesta_Bussines().Autenticado(idUsuario, datosApuesta.ValorApuesta)) { return(Unauthorized()); } if (new Apuesta_Bussines().validacionApuesta(datosApuesta)) { datosApuesta.IdUsuario = int.Parse(idUsuario); respuesta = new Apuesta_Bussines().generaApuesta(datosApuesta); } } else { throw new Exception("Debe Enviar los parametros {NumeroApuesta}, {ColorApuesta}, {ValorApuesta}, {IdRuleta} "); } return(Ok(respuesta)); }
public PendingDebitResp PendingDebit([FromBody] PendingDebitReq pendingDebitReq) { HttpRequestHeaders headers = this.Request.Headers; PendingDebitReq pendingDebitReq1 = new PendingDebitReq() { AccountNo = pendingDebitReq.AccountNo }; if (CBNController.ValidateToken(headers.GetValues("Authorization").First <string>().ToString().Substring("Bearer ".Length).Trim())) { this.logger.Info <PendingDebitReq>("Request {@value}", pendingDebitReq); CBNIntegration.Models.PendingDebit[] array = this.cBNIntegrationData.PendingDebit(pendingDebitReq1).ToArray(); int length = array.Length; PendingDebitResp pendingDebitResp = new PendingDebitResp() { Status = this.success.ResponseCode, Msg = this.success.ResponseMessage, Result = array }; this.logger.Info <PendingDebitResp>("Response {@value}", pendingDebitResp); return(pendingDebitResp); } PendingDebitResp pendingDebitResp1 = new PendingDebitResp() { Status = this.failed.ResponseCode, Msg = this.failed.ResponseMessage }; this.logger.Info <PendingDebitResp>("Response {@value}", pendingDebitResp1); return(pendingDebitResp1); }
public async Task <IHttpActionResult> PostClientUser([FromBody] ClientUser clientUser) { HttpRequestHeaders headers = this.Request.Headers; string app_key = string.Empty; if (headers.Contains("app_key")) { app_key = headers.GetValues("app_key").First(); } AuthApp app = await db.AuthApps.Where(a => a.auth_key.Equals(app_key)).FirstAsync(); if (app == null) { return(NotFound()); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (ClientUserExists(clientUser.email)) { return(Ok(db.ClientUsers.Where(c => c.email.Equals(clientUser.email)).First())); } db.ClientUsers.Add(clientUser); await db.SaveChangesAsync(); return(CreatedAtRoute("DefaultApi", new { id = clientUser.id }, clientUser)); }
public ValueProviderResult GetValue(string key) { var header = headers.FirstOrDefault(h => predicate(h, key)); if (header.Key.IsNotNullOrEmpty()) { key = header.Key; // Replace the passed in key with the header name var values = headers.GetValues(key); if (values.Count() > 1) // We got a list of values { return(new ValueProviderResult(values, null, CultureInfo.CurrentCulture)); } else { // We could have received multiple values (comma separated) or just one value var value = values.First(); values = value.Split(',').Select(x => x.Trim()).ToArray(); if (values.Count() > 1) { return(new ValueProviderResult(values, null, CultureInfo.CurrentCulture)); } else { return(new ValueProviderResult(value, value, CultureInfo.CurrentCulture)); } } } return(null); }
public async Task <IHttpActionResult> DeleteClientUser([FromBody] int id) { HttpRequestHeaders headers = this.Request.Headers; string app_key = string.Empty; if (headers.Contains("app_key")) { app_key = headers.GetValues("app_key").First(); } AuthApp app = await db.AuthApps.Where(a => a.auth_key.Equals(app_key)).FirstAsync(); if (app == null) { return(NotFound()); } ClientUser clientUser = await db.ClientUsers.FindAsync(id); if (clientUser == null) { return(NotFound()); } db.ClientUsers.Remove(clientUser); await db.SaveChangesAsync(); return(Ok(clientUser)); }
public async Task <IHttpActionResult> GetIngredient(int id) { HttpRequestHeaders headers = this.Request.Headers; string app_key = string.Empty; if (headers.Contains("app_key")) { app_key = headers.GetValues("app_key").First(); } AuthApp app = await db.AuthApps.Where(a => a.auth_key.Equals(app_key)).FirstAsync(); if (app == null) { return(NotFound()); } Ingredient ingredient = await db.Ingredients.FindAsync(id); if (ingredient == null) { return(NotFound()); } return(Ok(ingredient)); }