private void AddSecurityCodeExpectation(MockHttpMessageHandler mockHttp, TrustedDevice trustedDevice, string code) { var method = string.IsNullOrEmpty(code) ? HttpMethod.Put : HttpMethod.Post; var mockRequest = mockHttp .Expect(method, new RestUri(this.UrlProvider.TwoStepVerifyUrl, new { deviceId = trustedDevice.Id }).AbsoluteUri) .WithHeaders(new[] { new KeyValuePair <string, string>("Accept", "application/json"), new KeyValuePair <string, string>("Accept", "text/javascript"), new KeyValuePair <string, string>("X-Requested-With", "XMLHttpRequest"), new KeyValuePair <string, string>("X-Apple-Widget-Key", Expected_AuthToken_AuthServiceKey), new KeyValuePair <string, string>("x-apple-id-session-id", Expected_TwoStep_SessionId), new KeyValuePair <string, string>("scnt", Expected_TwoStep_Scnt) }) .Respond(HttpStatusCode.OK); if (method == HttpMethod.Post) { mockRequest.WithContent(this.JsonSerializer.Serialize(new { code })); mockHttp .Expect(HttpMethod.Get, this.UrlProvider.SessionUrl) .Respond(HttpStatusCode.OK, "application/json", this.JsonSerializer.Serialize(new Session { User = new User { EmailAddress = Expected_Session_User_EmailAddress, FullName = Expected_Session_User_FullName, Id = Expected_Session_User_Id } })); } }
private async Task <ClientContext> LoginWithTwoStepCodeAsync(TrustedDevice trustedDevice, string code) { var context = new ClientContext { AuthToken = new AuthToken { AuthServiceKey = Expected_AuthToken_AuthServiceKey, AuthServiceUrl = Expected_AuthToken_AuthServiceUrl }, TwoStepToken = new TwoStepToken { Scnt = Expected_TwoStep_Scnt, SessionId = Expected_TwoStep_SessionId } }; context.AddValue(trustedDevice); var mockHttp = new MockHttpMessageHandler(); this.AddSecurityCodeExpectation(mockHttp, trustedDevice, code); var client = this.CreateClient(new RestClient(mockHttp), this.UrlProvider); context = await client.LogonWithTwoStepCodeAsync(context, code); mockHttp.VerifyNoOutstandingExpectation(); return(context); }
public override DataContract.Common.IMovilwayApiResponse PerformKinacuOperation(DataContract.Common.IMovilwayApiRequest requestObject, KinacuWebService.SaleInterface kinacuWS, string sessionID) { //throw new NotImplementedException(); AddTrustedDeviceRequestBody request = (AddTrustedDeviceRequestBody)requestObject; AddTrustedDeviceResponseBody response = new AddTrustedDeviceResponseBody(); try { if (request.DeviceType != (int)cons.ACCESS_POSWEB) { response.ResponseCode = 90; response.ResponseMessage = "NO ESTA AUTORIZADO PARA ACCEDER A ESTE SERVICIO";//"ERROR INESPERADO"; response.TransactionID = 0; return(response); } //desnecriptar //String jsonString = request.InfoTokken; //int idUser = Utils.GetUserId(request.AuthenticationData.Username, cons.ACCESS_POSWEB); String jsonDecrypt = Cryptography.decrypt(request.InfoTokken); Dictionary <string, string> dictionary = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, string> >(jsonDecrypt); bool status = Convert.ToBoolean(dictionary["status"]); int type = Convert.ToInt32(dictionary["type"]); TrustedDevice device = new TrustedDevice() { UserId = request.AuthenticationData.Username, Token = dictionary["cookieMonster"], Hash = dictionary["hash"], IdType = type, FriendlyName = dictionary["friendlyName"], Description = dictionary["description"], Status = status? cons.DEVICE_ACTIVE: cons.DEVICE_TEMPORAL,//cons.DEVICE_ACTIVE, //status? cons.DEVICE_ACTIVE: cons.DEVICE_TEMPORAL, Secure = status, //IsActive = true, DateActivated = DateTime.MinValue, Model = dictionary["model"], OS = dictionary["os"], DateCreated = DateTime.Now, Ticks = Convert.ToInt64(dictionary["ticks"]) }; if (!device.IsValid()) { response.ResponseCode = 90; response.ResponseMessage = "LOS DATOS DEL DISPOSITIVO ESTAN INCOMPLETOS";//"ERROR INESPERADO"; response.TransactionID = 0; // return(response); } GenericApiResult <bool> result = Utils.AddTrustedDeviceNuevo(device); response.ResponseCode = result.ResponseCode; response.ResponseMessage = result.ResponseMessage; response.Result = result.ObjectResult; } catch (Exception ex) { response.ResponseCode = 500; response.ResponseMessage = ex.Message;//"ERROR INESPERADO"; response.TransactionID = 0; string mensaje = String.Concat("[API] ", base.LOG_PREFIX, " [AddTrustedDeviceProvider] [", ex.GetType().FullName, "] . Exception: ", ex.Message, ". ", ex.StackTrace); logger.ErrorLow(mensaje); } return(response); }
protected virtual async Task <LogonAuth> LogonWithTwoStepCodeAsync(ClientContext context, TrustedDevice trustedDevice, string code) { await Configure.AwaitFalse(); RestRequest request; if (string.IsNullOrEmpty(code)) { request = RestRequest.Put( new RestUri(this.UrlProvider.TwoStepVerifyUrl, new { deviceId = trustedDevice.Id }), this.GetTwoStepHeaders(context)); } else { request = RestRequest.Post( new RestUri(this.UrlProvider.TwoStepVerifyUrl, new { deviceId = trustedDevice.Id }), this.GetTwoStepHeaders(context), RestContentType.Json, new { code }); } var response = await this.SendAsync <LogonAuth>(context, request); return(response.Content); }
/// <summary> /// Acquires a the two-step authentication code to be send to the given trusted device. /// </summary> /// <returns>Returns a <see cref="T:ClientContext"/> to be used with all following client calls.</returns> /// <param name="context">The current context.</param> /// <param name="trustedDevice">Trusted device.</param> public async Task <ClientContext> AcquireTwoStepCodeAsync(ClientContext context, TrustedDevice trustedDevice) { await Configure.AwaitFalse(); var logonAuth = await this.LogonWithTwoStepCodeAsync(context, trustedDevice, null); context.Authentication = Authentication.TwoStepCode; context.LogonAuth = logonAuth; context.AddValue(trustedDevice); return(context); }
/// <summary> /// Valida que el acceso este activo y se ha valido /// </summary> /// <returns></returns> public void IsValidAccess(IMovilwayApiRequest request)//GenericApiResult<bool> { logger.InfoHigh(String.Concat(LOG_PREFIX, " IsValidAccess ")); bool acceso = true; // GenericApiResult<bool> result = new GenericApiResult<bool>(true); TrustedDevice device = null; //TODO quitar device = new TrustedDevice() { Status = cons.DEVICE_ACTIVE }; string message = ""; try { if (string.IsNullOrEmpty(request.AuthenticationData.Tokken)) { message = "NO SE ENVIO EL TOKKEN DE AUTENTICACION"; logger.ErrorHigh(String.Concat(LOG_PREFIX, message)); throw new Exception(message); } String jsonDecrypt = Cryptography.decrypt(request.AuthenticationData.Tokken); logger.InfoHigh(() => TagValue.New().Message(String.Concat(LOG_PREFIX, " ACCESS TOKKEN ")).Tag("DATA").Value(jsonDecrypt)); Dictionary <string, string> dictionary = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, string> >(jsonDecrypt); DateTime NowUtc = DateTime.UtcNow; DateTime AccessDtUtc = DateTime.ParseExact(dictionary["Fecha"], "yyyyMMdd HH:mm:ss", null); logger.InfoHigh(String.Concat("FECHAS UTC ", NowUtc.ToString("yyyyMMdd HH:mm:ss"), " - ", AccessDtUtc.ToString("yyyyMMdd HH:mm:ss"))); if ((NowUtc - AccessDtUtc) > t) { throw new SecurityException("EL TIEMPO DEL TOKKEN SE HA EXPIRADO"); } // // buscar en los accessos de la base de datos // string strConnString = ConfigurationManager.ConnectionStrings["SECURE_DB"].ConnectionString; // using (SqlConnection mySqlConnection = new SqlConnection(strConnString)) // { // mySqlConnection.Open(); // SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); // //select by serial // mySqlCommand.CommandText = @" // SELECT Device.DeviceId, Device.UserId, Device.Token, Device.Hash, Device.DeviceTypeId, Device.FriendlyName, Device.Description, Device.DateActivated, Device.Status, Device.LastAccess, Device.DateBlocked, // Device.Model, Device.OS, DeviceType.Name AS Type //FROM Device INNER JOIN // DeviceType ON Device.DeviceTypeId = DeviceType.DeviceTypeId WHERE Device.Token = @SerialTokken AND Device.UserId = @userId "; // //mySqlCommand.Parameters.AddWithValue("@SerialTokken", token); // //mySqlCommand.Parameters.AddWithValue("@userId", userid); // using (var reader = mySqlCommand.ExecuteReader()) // { // if (reader.HasRows && reader.Read()) // { // device = new TrustedDevice() // { // ID = (long)((int)reader["DeviceId"]), // UserId = (int)reader["UserId"], // Token = (string)reader["Token"], // Hash = (string)reader["Hash"], // //-- // IdType = (int)reader["DeviceTypeId"], // Type = (string)reader["Type"], // //-- // FriendlyName = (string)reader["FriendlyName"], // DateActivated = (DateTime)reader["DateActivated"], // Status = (Int16)reader["Status"], // }; // } // else // throw new Exception("NO SE ECONTRARON DATOS DEL ACCESO SEGUN LA AUTENTICACION"); // } // } if (device.Status != cons.DEVICE_ACTIVE) { message = "ACCESSO NO VALIDO"; logger.ErrorHigh(String.Concat(LOG_PREFIX, message)); //RECONSIDERAR RETORNULL throw new SecurityException(message); } } catch (Exception ex) { if (!(ex is SecurityException)) { logger.InfoHigh(String.Concat(LOG_PREFIX, " ERROR INESPERADO VALIDANDO ACCESO ", ex.Message, " - ", ex.StackTrace)); } throw; } }