Ejemplo n.º 1
0
        public void UserLockedOutForFailedAttemptsSignin()
        {
            string                 password     = Guid.Empty.ToString();
            IAppIdentity           appIdentity  = DelegatedAppIdentity.Master;
            RecognizedUserIdentity userIdentity = new RecognizedUserIdentity(
                RecognizedUserIdentity.Master.DocType,
                RecognizedUserIdentity.Master.DocNumber,
                password);

            TestContext.CurrentContext.DatabaseHelper().EnsureUserIsNotLocked(userIdentity.DocType, userIdentity.DocNumber);
            int maxFailedPasswordAttempt = TestContext.CurrentContext.DatabaseHelper().GetAppMaxFailedPasswordAttempt(appIdentity.ApiKey);

            void Authenticate() =>
            DelegatedApp.Initialize(CachePolicy.BypassCache)
            .RoutingTo(TestingEndpointProvider.Default)
            .WithIdentity(appIdentity)
            .Authenticate(userIdentity)
            .GetClient();

            AspenException exception;

            for (int index = 1; index < maxFailedPasswordAttempt; index++)
            {
                exception = Assert.Throws <AspenException>(Authenticate);
                Assert.That(exception.EventId, Is.EqualTo("97414"));
                Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
                StringAssert.IsMatch("Combinación de usuario y contraseña invalida. Por favor revise los valores ingresados e intente de nuevo", exception.Message);
            }

            exception = Assert.Throws <AspenException>(Authenticate);
            Assert.That(exception.EventId, Is.EqualTo("97415"));
            Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
            StringAssert.IsMatch("Usuario ha sido bloqueado por superar el número máximo de intentos de sesión inválidos", exception.Message);
            TestContext.CurrentContext.DatabaseHelper().EnsureUserIsNotLocked(userIdentity.DocType, userIdentity.DocNumber);
        }
Ejemplo n.º 2
0
        public void MismatchTokenBetweenUsersWhenUserSignedRequestThrows()
        {
            IAppIdentity commonAppIdentity = DelegatedAppIdentity.Master;

            IUserIdentity userIdentityMaster = RecognizedUserIdentity.Master;
            IDelegatedApp clientAppMaster    = DelegatedApp.Initialize(CachePolicy.BypassCache)
                                               .RoutingTo(TestingEndpointProvider.Default)
                                               .WithIdentity(commonAppIdentity)
                                               .Authenticate(userIdentityMaster)
                                               .GetClient();

            Assert.That(clientAppMaster, Is.Not.Null);
            Assert.That(clientAppMaster.AuthToken, Is.Not.Null);
            Assert.That(clientAppMaster.AuthToken.Token, Is.Not.Null);

            IUserIdentity userIdentityHelper = RecognizedUserIdentity.Helper;
            IDelegatedApp clientAppHelper    = DelegatedApp.Initialize(CachePolicy.BypassCache)
                                               .RoutingTo(TestingEndpointProvider.Default)
                                               .WithIdentity(commonAppIdentity)
                                               .Authenticate(userIdentityHelper)
                                               .GetClient();

            Assert.That(clientAppHelper, Is.Not.Null);
            Assert.That(clientAppHelper.AuthToken, Is.Not.Null);
            Assert.That(clientAppHelper.AuthToken.Token, Is.Not.Null);

            IPayloadClaimsManager mismatchTokenClaimBehavior = InvalidTokenPayloadClaim.WithClaimBehavior(() => clientAppHelper.AuthToken.Token);

            ServiceLocator.Instance.RegisterPayloadClaimsManager(mismatchTokenClaimBehavior);
            AspenException exception = Assert.Throws <AspenException>(() => clientAppMaster.Settings.GetDocTypes());

            Assert.That(exception.EventId, Is.EqualTo("15846"));
            Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
            StringAssert.IsMatch("No coinciden los datos recibidos del token vs los valores esperados. ¿Se modificaron los valores en tránsito o está utilizando el ApiKey en otra aplicación?", exception.Message);
        }
Ejemplo n.º 3
0
        public void NullOrEmptyApiKeyHeaderWhenUserSigninRequestThrows()
        {
            IList <IHeadersManager> headerBehaviors = new List <IHeadersManager>()
            {
                InvalidApiKeyHeader.WithHeaderBehavior(() => null),
                InvalidApiKeyHeader.WithHeaderBehavior(() => string.Empty),
                InvalidApiKeyHeader.WithHeaderBehavior(() => "     ")
            };

            foreach (IHeadersManager behavior in headerBehaviors)
            {
                AspenException exception = Assert.Throws <AspenException>(() =>
                {
                    ServiceLocator.Instance.RegisterHeadersManager(behavior);
                    DelegatedApp.Initialize(CachePolicy.BypassCache)
                    .RoutingTo(TestingEndpointProvider.Default)
                    .WithIdentity(DelegatedAppIdentity.Master)
                    .Authenticate(RecognizedUserIdentity.Master)
                    .GetClient();
                });

                Assert.That(exception.EventId, Is.EqualTo("20002"));
                Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
                StringAssert.IsMatch("Se requiere la cabecera personalizada 'X-PRO-Auth-App'", exception.Message);
            }
        }
Ejemplo n.º 4
0
        public void InvalidSecretFormatUserProfilePropertiesThrows()
        {
            string        fixedDocType              = "CC";
            string        randomDocNumber           = new Random().Next(1000000000, int.MaxValue).ToString();
            string        password                  = Guid.Empty.ToString();
            IAppIdentity  appIdentity               = DelegatedAppIdentity.Master;
            IUserIdentity tempUserIdentity          = new RecognizedUserIdentity(fixedDocType, randomDocNumber, password);
            Dictionary <string, string> userProfile = new Dictionary <string, string>()
            {
                { "Secret", password },
                { "SecretFormat", "InvalidTypeName" }
            };

            TestContext.CurrentContext.DatabaseHelper().EnsureUserAndProfileInfo(
                appIdentity.ApiKey,
                tempUserIdentity.DocType,
                tempUserIdentity.DocNumber,
                userProfile);

            AspenException exception = Assert.Throws <AspenException>(() =>
            {
                DelegatedApp.Initialize(CachePolicy.BypassCache)
                .RoutingTo(TestingEndpointProvider.Default)
                .WithIdentity(appIdentity)
                .Authenticate(tempUserIdentity)
                .GetClient();
            });

            TestContext.CurrentContext.DatabaseHelper().RemoveUserInfo(tempUserIdentity.DocType, tempUserIdentity.DocNumber);
            Assert.That(exception.EventId, Is.EqualTo("97417"));
            Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.InternalServerError));
            StringAssert.IsMatch("No es posible verificar las credenciales del usuario.", exception.Message);
        }
Ejemplo n.º 5
0
        public void ApiKeyScopeMismatchThrows()
        {
            AspenException exception = Assert.Throws <AspenException>(() =>
            {
                DelegatedApp.Initialize(CachePolicy.BypassCache)
                .RoutingTo(TestingEndpointProvider.Default)
                .WithIdentity(AutonomousAppIdentity.Master)
                .Authenticate(RecognizedUserIdentity.Master)
                .GetClient();
            });

            Assert.That(exception.EventId, Is.EqualTo("1000478"));
            Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
            StringAssert.IsMatch("ApiKey no tiene permisos para realizar la operación. Alcance requerido: 'Delegated'", exception.Message);
        }
Ejemplo n.º 6
0
        public void MissingTokenWhenSignedRequestThrows()
        {
            IDelegatedApp client = DelegatedApp.Initialize(CachePolicy.BypassCache)
                                   .RoutingTo(TestingEndpointProvider.Default)
                                   .WithIdentity(DelegatedAppIdentity.Master)
                                   .Authenticate(RecognizedUserIdentity.Master)
                                   .GetClient();

            // Se intenta usar una operación que requiere el token de autenticación.
            ServiceLocator.Instance.RegisterPayloadClaimsManager(InvalidTokenPayloadClaim.AvoidingClaim());
            AspenException exception = Assert.Throws <AspenException>(() => client.Settings.GetDocTypes());

            Assert.That(exception.EventId, Is.EqualTo("15852"));
            Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
            StringAssert.IsMatch("'Token' no puede ser nulo ni vacío", exception.Message);
        }
Ejemplo n.º 7
0
        public void MissingPayloadHeaderWhenUserSigninRequestThrows()
        {
            AspenException exception = Assert.Throws <AspenException>(() =>
            {
                ServiceLocator.Instance.RegisterHeadersManager(InvalidPayloadHeader.AvoidingHeader());
                DelegatedApp.Initialize(CachePolicy.BypassCache)
                .RoutingTo(TestingEndpointProvider.Default)
                .WithIdentity(DelegatedAppIdentity.Master)
                .Authenticate(RecognizedUserIdentity.Master)
                .GetClient();
            });

            Assert.That(exception.EventId, Is.EqualTo("20002"));
            Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
            StringAssert.IsMatch("Se requiere la cabecera personalizada 'X-PRO-Auth-Payload'", exception.Message);
        }
Ejemplo n.º 8
0
        public void NonceAlreadyProcessedWhenSignedRequestThrows()
        {
            // Se usa un nonce aleatorio con la autenticación del cliente...
            ServiceLocator.Instance.RegisterNonceGenerator(new SingleUseNonceGenerator());
            IDelegatedApp client = DelegatedApp.Initialize(CachePolicy.BypassCache)
                                   .RoutingTo(TestingEndpointProvider.Default)
                                   .WithIdentity(DelegatedAppIdentity.Master)
                                   .Authenticate(RecognizedUserIdentity.Master)
                                   .GetClient();

            // Se usa una operación luego de la autenticación con el mismo nonce y debe fallar ya que se está reutilizando...
            AspenException exception = Assert.Throws <AspenException>(() => client.Settings.GetDocTypes());

            Assert.That(exception.EventId, Is.EqualTo("15852"));
            Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
            StringAssert.IsMatch("Nonce ya procesado para su aplicación", exception.Message);
        }
Ejemplo n.º 9
0
        public void InvalidAppKeyCredentialThrows()
        {
            string         recognizedApiKey = AutonomousAppIdentity.Master.ApiKey;
            string         randomApiSecret  = Guid.NewGuid().ToString();
            AspenException exception        = Assert.Throws <AspenException>(() =>
            {
                DelegatedApp.Initialize(CachePolicy.BypassCache)
                .RoutingTo(TestingEndpointProvider.Default)
                .WithIdentity(recognizedApiKey, randomApiSecret)
                .Authenticate(RecognizedUserIdentity.Master)
                .GetClient();
            });

            Assert.That(exception.EventId, Is.EqualTo("20007"));
            Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
            StringAssert.IsMatch("El contenido de la cabecera personalizada 'X-PRO-Auth-Payload' no es válido", exception.Message);
        }
Ejemplo n.º 10
0
        public void UnrecognizedApiKeyThrows()
        {
            string randomApiKey = Guid.NewGuid().ToString();
            string apiKeySecret = AutonomousAppIdentity.Master.ApiSecret;

            AspenException exception = Assert.Throws <AspenException>(() =>
            {
                DelegatedApp.Initialize(CachePolicy.BypassCache)
                .RoutingTo(TestingEndpointProvider.Default)
                .WithIdentity(randomApiKey, apiKeySecret)
                .Authenticate(RecognizedUserIdentity.Master)
                .GetClient();
            });

            Assert.That(exception.EventId, Is.EqualTo("20005"));
            Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
            StringAssert.IsMatch("Identificador de ApiKey no válido para la cabecera personalizada 'X-PRO-Auth-App'", exception.Message);
        }
Ejemplo n.º 11
0
        public void UserLockoutThrows()
        {
            IUserIdentity userIdentity = RecognizedUserIdentity.Master;

            TestContext.CurrentContext.DatabaseHelper().EnsureUserIsLocked(userIdentity.DocType, userIdentity.DocNumber);
            AspenException exception = Assert.Throws <AspenException>(() =>
            {
                DelegatedApp.Initialize(CachePolicy.BypassCache)
                .RoutingTo(TestingEndpointProvider.Default)
                .WithIdentity(DelegatedAppIdentity.Master)
                .Authenticate(userIdentity)
                .GetClient();
            });

            Assert.That(exception.EventId, Is.EqualTo("97413"));
            Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
            StringAssert.IsMatch("Usuario está bloqueado por superar el número máximo de intentos de sesión inválidos", exception.Message);
            TestContext.CurrentContext.DatabaseHelper().EnsureUserIsNotLocked(userIdentity.DocType, userIdentity.DocNumber);
        }
Ejemplo n.º 12
0
        public void UnrecognizedUserThrows()
        {
            string fixedDocType    = "CC";
            string randomDocNumber = new Random().Next(1000000000, int.MaxValue).ToString();
            string password        = Guid.Empty.ToString();
            RecognizedUserIdentity unrecognizedUserIdentity = new RecognizedUserIdentity(fixedDocType, randomDocNumber, password);

            AspenException exception = Assert.Throws <AspenException>(() =>
            {
                DelegatedApp.Initialize(CachePolicy.BypassCache)
                .RoutingTo(TestingEndpointProvider.Default)
                .WithIdentity(DelegatedAppIdentity.Master)
                .Authenticate(unrecognizedUserIdentity)
                .GetClient();
            });

            Assert.That(exception.EventId, Is.EqualTo("97412"));
            Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
            StringAssert.IsMatch("Combinación de usuario y contraseña invalida. Por favor revise los valores ingresados e intente de nuevo", exception.Message);
        }
Ejemplo n.º 13
0
        public void NullOrEmptyTokenWhenSignedRequestThrows()
        {
            IDelegatedApp client = DelegatedApp.Initialize(CachePolicy.BypassCache)
                                   .RoutingTo(TestingEndpointProvider.Default)
                                   .WithIdentity(DelegatedAppIdentity.Master)
                                   .Authenticate(RecognizedUserIdentity.Master)
                                   .GetClient();

            IList <IPayloadClaimsManager> payloadBehaviors = new List <IPayloadClaimsManager>()
            {
                InvalidTokenPayloadClaim.WithClaimBehavior(() => null),
                InvalidTokenPayloadClaim.WithClaimBehavior(() => string.Empty),
                InvalidTokenPayloadClaim.WithClaimBehavior(() => "    ")
            };

            foreach (IPayloadClaimsManager behavior in payloadBehaviors)
            {
                ServiceLocator.Instance.RegisterPayloadClaimsManager(behavior);
                AspenException exception = Assert.Throws <AspenException>(() => client.Settings.GetDocTypes());
                Assert.That(exception.EventId, Is.EqualTo("15852"));
                Assert.That(exception.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
                StringAssert.IsMatch("'Token' no puede ser nulo ni vacío", exception.Message);
            }
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Obtiene un cliente para a partir de la aplicación delegada de pruebas, omitiendo los valores almacenados en memoria.
 /// </summary>
 /// <param name="cachePolicy">La política para el tratamiento de la información almacenada por caché.</param>
 /// <returns>Instancia de <see cref="IDelegatedApp"/> para interactuar con el servicio.</returns>
 public IDelegatedApp GetDelegatedClient(CachePolicy cachePolicy = CachePolicy.BypassCache) =>
 DelegatedApp.Initialize(cachePolicy)
 .RoutingTo(TestingEndpointProvider.Default)
 .WithIdentity(DelegatedAppIdentity.Master)
 .Authenticate(RecognizedUserIdentity.Master)
 .GetClient();