public void VerifyValidateAuthorityFalseForOnPremise()
        {
            AzureSessionInitializer.InitializeAzureSession();
            var authFactory = new AuthenticationFactory
            {
                TokenProvider = new MockAccessTokenProvider("testtoken", "testuser")
            };

            var subscriptionId = Guid.NewGuid();
            var account        = new AzureAccount
            {
                Id   = "testuser",
                Type = AzureAccount.AccountType.User,
            };

            account.SetTenants("123");
            var sub = new AzureSubscription
            {
                Id = subscriptionId.ToString(),
            };

            sub.SetTenant("123");
            var context = new AzureContext
                          (
                sub,
                account,
                new AzureEnvironment
            {
                Name      = "Katal",
                OnPremise = true,
                ActiveDirectoryAuthority = "http://ad.com",
                ActiveDirectoryServiceEndpointResourceId = "http://adresource.com"
            }
                          );

            var credential = authFactory.Authenticate(context.Account, context.Environment, "common", null, ShowDialog.Always, null);

            Assert.False(((MockAccessTokenProvider)authFactory.TokenProvider).AdalConfiguration.ValidateAuthority);
        }
Ejemplo n.º 2
0
        public ActionResult Login(LoginViewModel model)
        {
            var appuser = new AuthenticationFactory().AuthenticateAppUserLogin(model.Email, model.Password);

            if (appuser != null)
            {
                Session["gotitbackloggedinuser"] = appuser;
                if (appuser.Role == Usertype.Client.ToString())
                {
                    RedirectToAction("Create", "FoundItems");
                }
                if (appuser.Role == Usertype.Administrator.ToString())
                {
                    RedirectToAction("Index", "Contacts");
                }
                if (appuser.Role == Usertype.OverallAdministrator.ToString())
                {
                    RedirectToAction("Index", "Contacts");
                }
            }
            return(View(model));
            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            //var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: true);
            //switch (result)
            //{
            //    case SignInStatus.Success:
            //        return RedirectToLocal(returnUrl);
            //    case SignInStatus.LockedOut:
            //        return View("Lockout");
            //    case SignInStatus.RequiresVerification:
            //        return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            //    case SignInStatus.Failure:
            //    default:
            //        ModelState.AddModelError("", "Invalid login attempt.");
            //        return View(model);
            //}
        }
Ejemplo n.º 3
0
        public void CanGetServiceClientCredentialsWithAccessToken()
        {
            AzureSessionInitializer.InitializeAzureSession();
            IAuthenticatorBuilder authenticatorBuilder = new DefaultAuthenticatorBuilder();

            AzureSession.Instance.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => authenticatorBuilder);
            PowerShellTokenCacheProvider factory = new InMemoryTokenCacheProvider();

            AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => factory);
            string tenant     = Guid.NewGuid().ToString();
            string userId     = "*****@*****.**";
            var    armToken   = Guid.NewGuid().ToString();
            var    graphToken = Guid.NewGuid().ToString();
            var    kvToken    = Guid.NewGuid().ToString();
            var    account    = new AzureAccount
            {
                Id   = userId,
                Type = AzureAccount.AccountType.AccessToken
            };

            account.SetTenants(tenant);
            account.SetAccessToken(armToken);
            account.SetProperty(AzureAccount.Property.GraphAccessToken, graphToken);
            account.SetProperty(AzureAccount.Property.KeyVaultAccessToken, kvToken);
            var authFactory = new AuthenticationFactory();
            var environment = AzureEnvironment.PublicEnvironments.Values.First();
            var mockContext = new AzureContext()
            {
                Account = account
            };
            var credentials = authFactory.GetServiceClientCredentials(mockContext);

            VerifyAccessTokenInServiceClientCredentials(credentials, armToken);
            credentials = authFactory.GetServiceClientCredentials(mockContext, AzureEnvironment.Endpoint.Graph);
            VerifyAccessTokenInServiceClientCredentials(credentials, graphToken);
            credentials = authFactory.GetServiceClientCredentials(mockContext, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId);
            VerifyAccessTokenInServiceClientCredentials(credentials, kvToken);
        }
Ejemplo n.º 4
0
        public static TokenCloudCredentials GetTokenCloudCredentials(string username = null, SecureString password = null)
        {
            var authFactory = new AuthenticationFactory();

            var account = new AzureAccount {
                Type = AzureAccount.AccountType.User
            };

            if (username != null && password != null)
            {
                account.Id = username;
            }

            var env = AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud];

            ShowDialog dialog = username != null & password != null ? ShowDialog.Never : ShowDialog.Always;

            var accessToken =
                authFactory.Authenticate(account, env, AuthenticationFactory.CommonAdTenant, password, dialog)
                .AccessToken;

            return(new TokenCloudCredentials(accessToken));
        }
Ejemplo n.º 5
0
        public IEnumerable <IBusinessEntity> LoginUser(string LoginId, string Password, string UserIP)
        {
            IList <IBusinessEntity> response = new List <IBusinessEntity>();

            UserEntity userEntity;

            try
            {
                userEntity = GetUserDetailbyLoginId(LoginId);
            }
            catch (FinderException)
            {
                throw new BusinessException("Invalid User Name");
            }

            var isAuthenticated = AuthenticationFactory.GetAuthenticator().IsAuthenticated(userEntity.UserId, Password);

            if (isAuthenticated)
            {
                response.Add(SessionManager.CreateSession(LoginId, UserIP));
                response.Add(userEntity);
            }

            if (!isAuthenticated)
            {
                throw new BusinessException("Your password is invalid.");
            }

            if (userEntity.IsActive == false)
            {
                throw new BusinessException("Your account is disabled, Please contact the administrator.");
            }

            // AuditLogger.LogActivity(userEntity.UserEntityId.ToString(), DateTime.Now, ScreenActivityType.Login,11,"User Logon",-1,-1);
            return(response);
        }
Ejemplo n.º 6
0
        public void CanAuthenticateWithAccessToken()
        {
            AzureSessionInitializer.InitializeAzureSession();
            string tenant     = Guid.NewGuid().ToString();
            string userId     = "*****@*****.**";
            var    armToken   = Guid.NewGuid().ToString();
            var    graphToken = Guid.NewGuid().ToString();
            var    kvToken    = Guid.NewGuid().ToString();
            var    account    = new AzureAccount
            {
                Id   = userId,
                Type = AzureAccount.AccountType.AccessToken
            };

            account.SetTenants(tenant);
            account.SetAccessToken(armToken);
            account.SetProperty(AzureAccount.Property.GraphAccessToken, graphToken);
            account.SetProperty(AzureAccount.Property.KeyVaultAccessToken, kvToken);
            var authFactory   = new AuthenticationFactory();
            var environment   = AzureEnvironment.PublicEnvironments.Values.First();
            var checkArmToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null);

            VerifyToken(checkArmToken, armToken, userId, tenant);
            checkArmToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null, environment.ActiveDirectoryServiceEndpointResourceId);
            VerifyToken(checkArmToken, armToken, userId, tenant);
            var checkGraphToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null, AzureEnvironment.Endpoint.GraphEndpointResourceId);

            VerifyToken(checkGraphToken, graphToken, userId, tenant);
            checkGraphToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null, environment.GraphEndpointResourceId);
            VerifyToken(checkGraphToken, graphToken, userId, tenant);
            var checkKVToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null, environment.AzureKeyVaultServiceEndpointResourceId);

            VerifyToken(checkKVToken, kvToken, userId, tenant);
            checkKVToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId);
            VerifyToken(checkKVToken, kvToken, userId, tenant);
        }
Ejemplo n.º 7
0
        public ActionResult Login(LoginModel usuarioViewModel)
        {
            if (ModelState.IsValid)
            {
                Usuario usuario = new Usuario();
                usuario.UserName   = usuarioViewModel.UserName;
                usuario.Password   = usuarioViewModel.Password;
                usuario.Recordarme = usuarioViewModel.Recordarme;

                if (usuarioRepository.IsValid(usuario))
                {
                    var user = usuarioRepository.GetUserByUserName(usuario.UserName);

                    if (user.RolesEmpresa.Any(i => i.Rol_Id == 25))
                    {
                        if (!usuarioRepository.IsClienteActivo(usuario))
                        {
                            //vClientes cliente = new vClientes();
                            //string filtro = string.Format("Cuit = '{0}'", user.UserName);
                            //var dtcliente = cliente.GetByFilter(filtro);
                            //string rs = dtcliente.Rows[0][1].ToString();
                            string aviso = string.Format(" El Cliente {0} se encuentra inactivo, solicite su activacion", user.NombreApellido);
                            ModelState.AddModelError("", aviso);
                        }
                        else if (user.CambiarPass != true)
                        {
                            var authenticationService = AuthenticationFactory.CreateAuthentication();

                            var serializeModel = new CustomPrincipalSerializeModel();
                            serializeModel.UserID    = user.Id;
                            serializeModel.FirstName = user.NombreApellido;
                            serializeModel.UserName  = user.UserName;


                            var serializer = new JavaScriptSerializer();
                            var userData   = serializer.Serialize(serializeModel);

                            authenticationService.Login(user.UserName, user.Password, usuario.Recordarme, userData);

                            user.FechaUltimoAcceso = DateTime.Now;
                            usuarioRepository.Modify(user, user.Id);
                            AppSession.Init_Session(user.Id);
                            return(RedirectToAction("Index", "Home"));
                        }
                        else
                        {
                            return(UsuarioCambioPassword(usuario));
                        }
                    }
                    else if (user.CambiarPass != true)
                    {
                        var authenticationService = AuthenticationFactory.CreateAuthentication();

                        var serializeModel = new CustomPrincipalSerializeModel();
                        serializeModel.UserID    = user.Id;
                        serializeModel.FirstName = user.NombreApellido;
                        serializeModel.UserName  = user.UserName;


                        var serializer = new JavaScriptSerializer();
                        var userData   = serializer.Serialize(serializeModel);

                        authenticationService.Login(user.UserName, user.Password, usuario.Recordarme, userData);

                        user.FechaUltimoAcceso = DateTime.Now;
                        usuarioRepository.Modify(user, user.Id);
                        AppSession.Init_Session(user.Id);
                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        return(UsuarioCambioPassword(usuario));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Error al validar datos ingresados, intente nuevamente");
                }
            }
            return(View(usuarioViewModel));
        }
Ejemplo n.º 8
0
 public ActionResult Logout()
 {
     AuthenticationFactory.CreateAuthentication().Logout();
     return(RedirectToAction("Login", "Usuario"));
 }
Ejemplo n.º 9
0
        public ActionResult UsuarioCambioPassword([Bind(Include = "UserName,Password,NuevaPassword,NuevaPasswordAgain")] ChangePasswordModel changeUsuario)
        {
            ViewBag.FirstTime = null;
            if (ModelState.IsValid)
            {
                Usuario user = new Usuario();
                user.UserName = changeUsuario.UserName;
                user.Password = changeUsuario.Password;

                if (usuarioRepository.IsValid(user))
                {
                    if (changeUsuario.NuevaPassword.Trim().Equals(changeUsuario.NuevaPasswordAgain.Trim()))
                    {
                        if (changeUsuario.NuevaPassword.Length >= 4)
                        {
                            var usuario = usuarioRepository.GetUserByUserName(changeUsuario.UserName);

                            usuario.Password          = changeUsuario.NuevaPassword;
                            usuario.FechaUltimoAcceso = DateTime.Now;
                            usuario.CambiarPass       = false;

                            usuarioRepository.Modify(usuario, user.Id);

                            var authenticationService = AuthenticationFactory.CreateAuthentication();

                            var serializeModel = new CustomPrincipalSerializeModel();
                            serializeModel.UserID    = usuario.Id;
                            serializeModel.FirstName = usuario.NombreApellido;
                            serializeModel.UserName  = usuario.UserName;

                            var serializer = new JavaScriptSerializer();
                            var userData   = serializer.Serialize(serializeModel);

                            authenticationService.Login(usuario.UserName, usuario.Password, usuario.Recordarme, userData);

                            return(RedirectToAction("Index", "Home"));
                        }
                        else
                        {
                            ModelState.AddModelError("", "La nueva Password debe contener más de 3 caracteres");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "Las Password no coinciden");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Error al validar datos ingresados, intente nuevamente");
                }
            }
            else
            {
                changeUsuario.Password           = null;
                changeUsuario.NuevaPassword      = null;
                changeUsuario.NuevaPasswordAgain = null;
            }

            return(View("UsuarioCambioPassword", changeUsuario));
        }
Ejemplo n.º 10
0
 public AuthenticationServiceTests()
 {
     _factory = new AuthenticationFactory();
     _service = new AuthenticationService();
 }
Ejemplo n.º 11
0
 public Startup(IConfiguration configuration)
 {
     Configuration = configuration;
     AuthenticationFactory.CreateAuthentication(AuthenticationFactory.CustomAuthType.Jwt, new TimeSpan(0, 30, 0));
 }
 public static void Initialise()
 {
     AuthenticationFactory.SetCurrent(new FormsAuthenticationFactory());
 }
Ejemplo n.º 13
0
 protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
 {
     AuthenticationFactory.CreateAuthentication().PostAuthenticateRequest();
 }
Ejemplo n.º 14
0
        public static IHtmlString DrawMenuItems(this HtmlHelper html)
        {
            StringBuilder sb = new StringBuilder();

            var currenUser   = AuthenticationFactory.CreateAuthentication().GetUser();
            var currenModulo = GetBaseController(html).GetCurrenModulo();

            currenUser.RolesEmpresa = AppSession.RolesEmpresa;
            //  currenUser.UsuarioRolClientes = AppSession.RolesCliente;
            //var listModulosSistema = moduloRepository.GetFiltered(o=>o.Visible, p=>p.Parent).OrderBy(o=>o.Descripcion);
            var listModulosSistema = moduloRepository.GetModulosUser(currenUser.RolesEmpresa, AppSession.Modulos);
            var menuVM             = MenuViewModel.CreateVM(null, listModulosSistema.ToList());

            //   var listModulosPermiso = usuarioRepository.GetRolesEmpresaByUsuarioId(currenUser.UserID).Select(o=>o.Rol.ModulosPermiso);

            //foreach (var ob in listModulosPermiso)
            //{
            //    foreach (var modulo in ob.GroupBy(o => o.Modulo_Id).Select(group => group.First()))
            //    {

            //  //      menuVM.Where(o => o.Children.se == modulo.Modulo_Id).Any();

            //    }
            //}

            string classExpand        = "class='hasSub current'";
            string classAExpand       = "class='expand rotateOut'";
            string classSubExpandShow = "class='sub expand show'";
            string classCurrent       = "class='current'";

            foreach (var menuItem in menuVM)
            {
                if (IsInCurrentModulo(currenModulo, menuItem.MenuId))
                {
                    sb.Append("<li " + classExpand + ">");

                    sb.Append("<a href='#' " + classAExpand + ">");
                }
                else
                {
                    sb.Append("<li >");
                    sb.Append("<a href='#'>");
                }
                sb.Append(" <span class='icon'><i class='" + menuItem.Class + "'></i></span>");
                sb.Append(" <span class='txt'>" + menuItem.Descripcion + "</span>");
                sb.Append("</a>");

                if (menuItem.Children.Count() > 0)
                {
                    if (IsInCurrentModulo(currenModulo, menuItem.MenuId))
                    {
                        sb.Append("<ul " + classSubExpandShow + " >");
                    }
                    else
                    {
                        sb.Append("<ul class='sub'>");
                    }

                    #region Sub Menu 1° Nivel
                    foreach (var child in menuItem.Children)
                    {
                        if (currenModulo.Id == menuItem.MenuId)
                        {
                            sb.Append("<li " + classCurrent + " >");
                        }
                        else
                        {
                            sb.Append("<li>");
                        }

                        if (child.URL != string.Empty && child.URL != null)
                        {
                            if (child.URL.ToUpper().StartsWith("HTTP"))
                            {
                                if (IsInCurrentModulo(currenModulo, child.MenuId))
                                {
                                    sb.Append("<a href='" + child.URL + "' " + classExpand + " >");
                                }
                                else
                                {
                                    sb.Append("<a href='" + child.URL + "'>");
                                }
                            }
                            else
                            {
                                if (IsInCurrentModulo(currenModulo, child.MenuId))
                                {
                                    sb.Append("<a href='/" + child.URL + "' " + classExpand + " >");
                                }
                                else
                                {
                                    sb.Append("<a href='/" + child.URL + "'>");
                                }
                            }
                        }
                        else
                        if (IsInCurrentModulo(currenModulo, child.MenuId))
                        {
                            sb.Append("<a href='#'>");
                        }
                        else
                        {
                            sb.Append("<a href='#' " + classExpand + " >");
                        }

                        sb.Append("<span class='icon'><i class='" + (child.Class != null && child.Class != string.Empty ? child.Class : "") + "'></i></span>");
                        sb.Append(" <span class='txt'>" + child.Descripcion + "</span>");
                        sb.Append("</a>");

                        //if(child.Children.Count() > 0)
                        //    sb.Append("<ul class='sub'>");

                        if (child.Children.Count() > 0)
                        {
                            if (IsInCurrentModulo(currenModulo, child.MenuId))
                            {
                                sb.Append("<ul " + classSubExpandShow + " >");
                            }
                            else
                            {
                                sb.Append("<ul class='sub'>");
                            }
                        }

                        #region Sub Menu 2° Nivel
                        foreach (var subchild in child.Children)
                        {
                            //   sb.Append("<li>");
                            if (currenModulo.Id == menuItem.MenuId)
                            {
                                sb.Append("<li " + classCurrent + " >");
                            }
                            else
                            {
                                sb.Append("<li>");
                            }

                            if (subchild.URL != string.Empty && subchild.URL != null)
                            {
                                if (subchild.URL.ToUpper().StartsWith("HTTP"))
                                {
                                    if (IsInCurrentModulo(currenModulo, subchild.MenuId))
                                    {
                                        sb.Append("<a href='" + subchild.URL + "' " + classExpand + " >");
                                    }
                                    else
                                    {
                                        sb.Append("<a href='" + subchild.URL + "'>");
                                    }
                                }
                                else
                                {
                                    if (IsInCurrentModulo(currenModulo, subchild.MenuId))
                                    {
                                        sb.Append("<a href='/" + subchild.URL + "' " + classExpand + " >");
                                    }
                                    else
                                    {
                                        sb.Append("<a href='/" + subchild.URL + "'>");
                                    }
                                }
                            }
                            else
                            if (IsInCurrentModulo(currenModulo, subchild.MenuId))
                            {
                                sb.Append("<a href='#'>");
                            }
                            else
                            {
                                sb.Append("<a href='#' " + classExpand + " >");
                            }

                            sb.Append("<span class='icon'><i class='" + (subchild.Class != null && subchild.Class != string.Empty ? subchild.Class : "") + "'></i></span>");
                            sb.Append(" <span class='txt'>" + subchild.Descripcion + "</span>");
                            sb.Append("</a>");

                            //if (subchild.Children.Count() > 0)
                            //    sb.Append("<ul class='sub'>");

                            if (subchild.Children.Count() > 0)
                            {
                                if (IsInCurrentModulo(currenModulo, subchild.MenuId))
                                {
                                    sb.Append("<ul " + classSubExpandShow + " >");
                                }
                                else
                                {
                                    sb.Append("<ul class='sub'>");
                                }
                            }

                            #region Sub Menu 3° Nivel
                            foreach (var subsubchild in subchild.Children)
                            {
                                //   sb.Append("<li>");
                                if (currenModulo.Id == subsubchild.MenuId)
                                {
                                    sb.Append("<li " + classCurrent + " >");
                                }
                                else
                                {
                                    sb.Append("<li>");
                                }

                                if (subsubchild.URL != string.Empty && subsubchild.URL != null)
                                {
                                    if (subsubchild.URL.ToUpper().StartsWith("HTTP"))
                                    {
                                        if (IsInCurrentModulo(currenModulo, subsubchild.MenuId))
                                        {
                                            sb.Append("<a href='" + subsubchild.URL + "' " + classExpand + " >");
                                        }
                                        else
                                        {
                                            sb.Append("<a href='" + subsubchild.URL + "'>");
                                        }
                                    }
                                    else
                                    {
                                        if (IsInCurrentModulo(currenModulo, subsubchild.MenuId))
                                        {
                                            sb.Append("<a href='/" + subsubchild.URL + "' " + classExpand + " >");
                                        }
                                        else
                                        {
                                            sb.Append("<a href='/" + subsubchild.URL + "'>");
                                        }
                                    }
                                }

                                else
                                if (IsInCurrentModulo(currenModulo, subsubchild.MenuId))
                                {
                                    sb.Append("<a href='#'>");
                                }
                                else
                                {
                                    sb.Append("<a href='#' " + classExpand + " >");
                                }

                                sb.Append("<span class='icon'><i class='" + (subsubchild.Class != null && subsubchild.Class != string.Empty ? subsubchild.Class : "") + "'></i></span>");
                                sb.Append(" <span class='txt'>" + subsubchild.Descripcion + "</span>");
                                sb.Append("</a>");

                                sb.Append("</li>");
                            }
                            #endregion

                            if (subchild.Children.Count() > 0)
                            {
                                sb.Append("</ul>");
                            }
                            sb.Append("</li>");
                        }

                        #endregion

                        if (child.Children.Count() > 0)
                        {
                            sb.Append("</ul>");
                        }
                        sb.Append("</li>");
                    }
                    #endregion

                    if (menuItem.Children.Count() > 0)
                    {
                        sb.Append("</ul>");
                    }
                    sb.Append("</li>");
                }
            }

            //foreach (var ob in listRolEmpresa.Select(o => o.Rol.ModulosPermiso))
            //{
            //    foreach (var modulo in ob.GroupBy(o=>o.Modulo_Id).Select(group => group.First()))
            //    {
            //       var moduloSistema= listModulosSistema.Where(o => o.Id == modulo.Modulo_Id).FirstOrDefault();
            //       var result = moduloSistema.Parent.
            //    }
            //}

            return(new HtmlString(sb.ToString()));
        }
Ejemplo n.º 15
0
        public void CanAuthenticateUsingMSIObjectId()
        {
            AzureSessionInitializer.InitializeAzureSession();
            IAuthenticatorBuilder authenticatorBuilder = new DefaultAuthenticatorBuilder();

            AzureSession.Instance.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => authenticatorBuilder);
            PowerShellTokenCacheProvider factory = new InMemoryTokenCacheProvider();

            AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => factory);
            string expectedAccessToken = Guid.NewGuid().ToString();

            _output.WriteLine("Expected access token for ARM URI: {0}", expectedAccessToken);
            string expectedToken2 = Guid.NewGuid().ToString();
            string tenant         = Guid.NewGuid().ToString();

            _output.WriteLine("Expected access token for graph URI: {0}", expectedToken2);
            string userId  = Guid.NewGuid().ToString();
            var    account = new AzureAccount
            {
                Id   = userId,
                Type = AzureAccount.AccountType.ManagedService
            };
            var environment      = AzureEnvironment.PublicEnvironments["AzureCloud"];
            var expectedResource = environment.ActiveDirectoryServiceEndpointResourceId;
            var builder          = new UriBuilder(AuthenticationFactory.DefaultMSILoginUri);

            builder.Query = $"resource={Uri.EscapeDataString(environment.ActiveDirectoryServiceEndpointResourceId)}&object_id={userId}&api-version=2018-02-01";
            var defaultUri = builder.Uri.ToString();

            var customBuilder = new UriBuilder(AuthenticationFactory.DefaultMSILoginUri);

            customBuilder.Query = $"resource={Uri.EscapeDataString(environment.GraphEndpointResourceId)}&object_id={userId}&api-version=2018-02-01";
            var customUri = customBuilder.Uri.ToString();

            var responses = new Dictionary <string, ManagedServiceTokenInfo>(StringComparer.OrdinalIgnoreCase)
            {
                { defaultUri, new ManagedServiceTokenInfo {
                      AccessToken = expectedAccessToken, ExpiresIn = 3600, Resource = expectedResource
                  } },
                { customUri, new ManagedServiceTokenInfo {
                      AccessToken = expectedToken2, ExpiresIn = 3600, Resource = environment.GraphEndpointResourceId
                  } }
            };

            AzureSession.Instance.RegisterComponent(HttpClientOperationsFactory.Name, () => TestHttpOperationsFactory.Create(responses, _output), true);
            var             authFactory = new AuthenticationFactory();
            IRenewableToken token       = (IRenewableToken)authFactory.Authenticate(account, environment, tenant, null, null, null);

            _output.WriteLine($"Received access token for default Uri ${token.AccessToken}");
            Assert.Equal(expectedAccessToken, token.AccessToken);
            Assert.Equal(3600, Math.Round(token.ExpiresOn.Subtract(DateTimeOffset.Now).TotalSeconds));
            var account2 = new AzureAccount
            {
                Id   = userId,
                Type = AzureAccount.AccountType.ManagedService
            };
            var token2 = authFactory.Authenticate(account2, environment, tenant, null, null, null, AzureEnvironment.Endpoint.GraphEndpointResourceId);

            _output.WriteLine($"Received access token for custom Uri ${token2.AccessToken}");
            Assert.Equal(expectedToken2, token2.AccessToken);
            var token3 = authFactory.Authenticate(account, environment, tenant, null, null, null, "bar");

            Assert.Throws <InvalidOperationException>(() => token3.AccessToken);
        }
Ejemplo n.º 16
0
        public HttpResponseMessage Verification(string UserId, string Userkey)
        {
            bool result = AuthenticationFactory.Authentication().ApiVerification(UserId, Userkey);

            return(ToJson(result));
        }
Ejemplo n.º 17
0
        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            if (HttpContext.Current.User != null)
            {
                return;
            }

            HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

            if (authCookie != null)
            {
                if (!string.IsNullOrEmpty(authCookie.Value))
                {
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
                    if (ticket == null)
                    {
                        return;
                    }


                    try
                    {
                        Business.DAL.UsuarioRepository usuarioRepo = new Business.DAL.UsuarioRepository();
                        var authenticationService = AuthenticationFactory.CreateAuthentication();
                        var user           = usuarioRepo.GetUserByUserName(ticket.Name, true);
                        var serializeModel = new CustomPrincipalSerializeModel();
                        serializeModel.UserID    = user.Id;
                        serializeModel.FirstName = user.NombreApellido;
                        serializeModel.UserName  = user.UserName;


                        var serializer = new JavaScriptSerializer();
                        var userData   = serializer.Serialize(serializeModel);

                        authenticationService.Login(user.NombreApellido, user.Password, user.Recordarme, userData);

                        user.FechaUltimoAcceso = DateTime.Now;
                        usuarioRepo.Modify(user, user.Id);
                        // AppSession.Init_Session(user.Id);
                        //    u = uow.LoginWithTicket(ticket.Name);
                    }
                    catch (Exception)
                    {
                        HttpContext.Current.User = null;
                        return;
                    }

                    //  HttpContext.Current.User = new Business.UserPrincipal(u);
                }
            }

            /*else
             * {
             * Business.UnitOfWork uow = new Business.UnitOfWork();
             * Business.User u         = null;
             * try
             * {
             *     u = uow.LoginAsAnonymous();
             * }
             * catch (Exception)
             * {
             *     HttpContext.Current.User = null;
             *     return;
             * }
             *
             * HttpContext.Current.User = new Business.UserPrincipal(u);
             * }*/
        }
Ejemplo n.º 18
0
 public PulsarClientConfigBuilder Authentication(string authPluginClassName, IDictionary <string, string> authParams)
 {
     _conf.Authentication = AuthenticationFactory.Create(authPluginClassName, authParams);
     return(this);
 }
Ejemplo n.º 19
0
        private void LoadXml(XElement SourceXml)
        {
            XElement x;
            TsPage   currPage = null;
            TsPage   prevPage = null;

            IEnumerable <XElement> pagesXml;

            if (SourceXml != null)
            {
                this._debug    = XmlHandler.GetBoolFromXAttribute(SourceXml, "Debug", this._debug);
                this._livedata = XmlHandler.GetBoolFromXAttribute(SourceXml, "LiveData", this._livedata);

                //Set show grid lines after pages and columns have been created.
                x = SourceXml.Element("ShowGridLines");
                if ((x != null) && (this._prodmode == false))
                {
                    this.ShowGridLines = true;
                }

                x = SourceXml.Element("UseTouchDefaults");
                if (x != null)
                {
                    this.UseTouchDefaults = true;
                }

                //turn hardware eval on or off
                x = SourceXml.Element("HardwareEval");
                if (x != null)
                {
                    this._hardwareevaluator = new HardwareEvaluator();
                }

                //start layout import
                this.TsMainWindow = new TsMainWindow(this.ParentWindow, SourceXml);

                this._buttons = new TsButtons();
                this._buttons.LoadXml(SourceXml.Element("Buttons"));

                PageDefaults pagedef = new PageDefaults();

                x = SourceXml.Element("Heading");
                if (x != null)
                {
                    pagedef.PageHeader = new TsPageHeader(this.TsMainWindow, x);
                }
                else
                {
                    pagedef.PageHeader = new TsPageHeader();
                }

                x = SourceXml.Element("LeftPane");
                if (x != null)
                {
                    pagedef.LeftPane = new TsPane(x);
                }
                else
                {
                    pagedef.LeftPane = new TsPane();
                }

                x = SourceXml.Element("RightPane");
                if (x != null)
                {
                    pagedef.RightPane = new TsPane(x);
                }
                else
                {
                    pagedef.RightPane = new TsPane();
                }

                pagedef.Buttons    = this._buttons;
                pagedef.MainWindow = this.TsMainWindow;


                this.TsMainWindow.LoadXml(SourceXml);
                GuiTimeout.Init(SourceXml.Element("Timeout"));

                foreach (XElement xauth in SourceXml.Elements("Authentication"))
                {
                    this._authlibrary.AddAuthenticator(AuthenticationFactory.GetAuthenticator(xauth));
                }

                //now read in the options and add to a dictionary for later use
                pagesXml = SourceXml.Elements("Page");
                if (pagesXml != null)
                {
                    //Debug.WriteLine("pagesXml not null");
                    foreach (XElement xPage in pagesXml)
                    {
                        #region
                        //Debug.WriteLine("creating new page");
                        if (currPage != null)
                        {
                            //record the last page as the prevPage
                            prevPage = currPage;
                            currPage = new TsPage(this.TsMainWindow, xPage, pagedef);
                        }
                        else
                        {
                            currPage         = new TsPage(this.TsMainWindow, xPage, pagedef);
                            currPage.IsFirst = true;
                        }

                        //create the new page and assign the next page/prev page links
                        currPage.PreviousPage = prevPage;
                        if (prevPage != null)
                        {
                            prevPage.NextPage = currPage;
                        }

                        this._pages.Add(currPage);
                        currPage.Page.Loaded += this.OnWindowLoaded;
                        #endregion
                    }

                    //currPage.IsLast = true;
                }

                x = SourceXml.Element("NoUI");
                if (x != null)
                {
                    this._nouicontainer = new NoUIContainer(x);
                }
            }

            LoggerFacade.Info("Config load finished");
            this.ConfigLoadFinished?.Invoke(this, null);
        }
 public void CheckThatProviderFactoryDoesNotInitializeInvalidInstance()
 {
     AuthenticationFactory.GetAuthenticationProvider("NonConfiguredDbAuthenticationProviderName");
 }
Ejemplo n.º 21
0
        public ActionResult AppLogin(FormCollection collectedValues)
        {
            var appUser = new AuthenticationFactory().AuthenticateAppUserLogin(collectedValues["Email"].Trim(),
                                                                               collectedValues["Password"].Trim());
            var model         = Session["newsmodel"] as News;
            var activityModel = Session["activitymodel"] as SchoolDiscussion;

            if (appUser != null)
            {
                Session["bhuinfologgedinuser"] = appUser;
                if (appUser.Role == UserType.Administrator.ToString())
                {
                    if (model != null)
                    {
                        Session["newsmodel"]           = null;
                        Session["bhuinfologgedinuser"] = appUser;
                        return(RedirectToAction("ViewNewsDetails", "Home",
                                                new { Id = new Md5Ecryption().EncryptPrimaryKey(model.NewsId.ToString(), true) }));
                    }
                    if (activityModel != null)
                    {
                        var schoolDiscussionId = activityModel.SchoolDiscussionId;
                        Session["activitymodel"]       = null;
                        Session["bhuinfologgedinuser"] = appUser;
                        return(RedirectToAction("Activity", "SchoolDiscussions",
                                                new { Id = new Md5Ecryption().EncryptPrimaryKey(schoolDiscussionId.ToString(), true) }));
                    }
                    Session["bhuinfologgedinuser"] = appUser;
                    TempData["login"] = "******" + appUser.DisplayName + "!";
                    return(RedirectToAction("Dashboard", "Home"));
                }
                if (appUser.Role == UserType.Manager.ToString())
                {
                    if (model != null)
                    {
                        var newsId = model.NewsId;
                        Session["newsmodel"]           = null;
                        Session["bhuinfologgedinuser"] = appUser;
                        return(RedirectToAction("ViewNewsDetails", "Home",
                                                new { Id = new Md5Ecryption().EncryptPrimaryKey(newsId.ToString(), true) }));
                    }
                    if (activityModel != null)
                    {
                        var schoolDiscussionId = activityModel.SchoolDiscussionId;
                        Session["activitymodel"]       = null;
                        Session["bhuinfologgedinuser"] = appUser;
                        return(RedirectToAction("Activity", "SchoolDiscussions",
                                                new { Id = new Md5Ecryption().EncryptPrimaryKey(schoolDiscussionId.ToString(), true) }));
                    }
                    Session["bhuinfologgedinuser"] = appUser;
                    bool remember = Convert.ToBoolean(collectedValues["RememberMe"]);
                    if (remember)
                    {
                        var authTicket = new FormsAuthenticationTicket(
                            1,
                            appUser.DisplayName,
                            DateTime.Now,
                            DateTime.Now.AddHours(72),
                            appUser.RememberMe,
                            "", //roles
                            "/"
                            );
                        //encrypt the ticket and add it to a cookie
                        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
                                                           FormsAuthentication.Encrypt(authTicket));
                        Response.Cookies.Add(cookie);
                    }
                    TempData["login"] = "******" + appUser.DisplayName + "!";
                    return(RedirectToAction("Index", "News"));
                }

                if (appUser.Role == UserType.Student.ToString())
                {
                    if (model != null)
                    {
                        var newsId = model.NewsId;
                        Session["newsmodel"]           = null;
                        Session["bhuinfologgedinuser"] = appUser;
                        return(RedirectToAction("ViewNewsDetails", "Home",
                                                new { Id = new Md5Ecryption().EncryptPrimaryKey(newsId.ToString(), true) }));
                    }
                    if (activityModel != null)
                    {
                        var schoolDiscussionId = activityModel.SchoolDiscussionId;
                        Session["activitymodel"]       = null;
                        Session["bhuinfologgedinuser"] = appUser;
                        return(RedirectToAction("Activity", "SchoolDiscussions",
                                                new { Id = new Md5Ecryption().EncryptPrimaryKey(schoolDiscussionId.ToString(), true) }));
                    }
                    Session["bhuinfologgedinuser"] = appUser;
                    TempData["login"] = "******" + appUser.DisplayName + "!";
                    return(RedirectToAction("Dashboard", "Home"));
                }
            }
            TempData["login"] = "******";

            return(RedirectToAction("Login", "Account"));
        }
        public void CanAuthenticateUsingMSIDefault()
        {
            AzureSessionInitializer.InitializeAzureSession();
            IAuthenticatorBuilder authenticatorBuilder = new DefaultAuthenticatorBuilder();

            AzureSession.Instance.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => authenticatorBuilder);
            PowerShellTokenCacheProvider factory = new InMemoryTokenCacheProvider();

            AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => factory);
            var msalAccessTokenAcquirerFactory = new MsalAccessTokenAcquirerFactory();

            AzureSession.Instance.RegisterComponent(nameof(MsalAccessTokenAcquirerFactory), () => msalAccessTokenAcquirerFactory, true);

            string expectedAccessToken = Guid.NewGuid().ToString();

            _output.WriteLine("Expected access token for default URI: {0}", expectedAccessToken);
            var mockAzureCredentialFactory = new MockAzureCredentialFactory();
            MockManagedIdentityCredential mockManagedIdentityCredential = null;

            mockAzureCredentialFactory.CredentialFactory = (clientId) =>
            {
                return(mockManagedIdentityCredential = new MockManagedIdentityCredential(clientId)
                {
                    TokenFactory = () => new AccessToken(expectedAccessToken, DateTimeOffset.Now)
                });
            };
            AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => (AzureCredentialFactory)mockAzureCredentialFactory, true);

            string expectedToken2 = Guid.NewGuid().ToString();
            string tenant         = Guid.NewGuid().ToString();

            _output.WriteLine("Expected access token for custom URI: {0}", expectedToken2);
            string userId  = Constants.DefaultMsiAccountIdPrefix + "12345";
            var    account = new AzureAccount
            {
                Id   = userId,
                Type = AzureAccount.AccountType.ManagedService
            };
            var environment      = AzureEnvironment.PublicEnvironments["AzureCloud"];
            var expectedResource = environment.ActiveDirectoryServiceEndpointResourceId;
            var builder          = new UriBuilder(AuthenticationFactory.DefaultBackupMSILoginUri);
            //builder.Query = $"resource={Uri.EscapeDataString(environment.ActiveDirectoryServiceEndpointResourceId)}&api-version=2018-02-01";
            //var defaultUri = builder.Uri.ToString();

            //var responses = new Dictionary<string, ManagedServiceTokenInfo>(StringComparer.OrdinalIgnoreCase)
            //{
            //    {defaultUri, new ManagedServiceTokenInfo { AccessToken = expectedAccessToken, ExpiresIn = 3600, Resource=expectedResource}},
            //    {"http://*****:*****@foo.com";
            var account2 = new AzureAccount
            {
                Id   = userId2,
                Type = AzureAccount.AccountType.ManagedService
            };

            //account2.SetProperty(AzureAccount.Property.MSILoginUri, "http://myfunkyurl:10432/oauth2/token");
            expectedAccessToken = expectedToken2;
            var token2 = authFactory.Authenticate(account2, environment, tenant, null, null, null, "foo");

            _output.WriteLine($"Received access token for custom Uri ${token2.AccessToken}");
            Assert.Equal(expectedToken2, token2.AccessToken);
            Assert.Equal(userId2, mockManagedIdentityCredential.AccountId);
            //var token3 = authFactory.Authenticate(account, environment, tenant, null, null, null, "bar");
            //Assert.Throws<InvalidOperationException>(() => token3.AccessToken);
        }
Ejemplo n.º 23
0
 public static void Initialise()
 {
     // LoggerFactory.SetCurrent(new TraceSourceLogFactory());
     AuthenticationFactory.SetCurrent(new FormsAuthenticationFactory());
 }
Ejemplo n.º 24
0
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var appUser = new AuthenticationFactory().AuthenticateAppUserLogin(model.Email, model.Password);

            if (appUser != null)
            {
                var restaurant = _db.Restaurants.Find(appUser.RestaurantId);
                var userRole   = _db.Roles.Find(appUser.RoleId);
                if (appUser.RestaurantId != null)
                {
                    var restaurantStructure = _db.RestaurantStructures.SingleOrDefault(n => n.RestaurantId == restaurant.RestaurantId);
                    Session["restaurantStructure"] = restaurantStructure;
                }

                //store objects in a session
                Session["odarmsloggedinuser"] = appUser;
                Session["restaurant"]         = restaurant;
                Session["role"] = userRole;

                //create the authentication ticket
                var authTicket = new FormsAuthenticationTicket(
                    1,
                    appUser.AppUserId.ToString(), //user id
                    DateTime.Now,
                    DateTime.Now.AddMinutes(40),  //expiry
                    true,                         //true to remember
                    userRole.Name,                //roles
                    Url.Action("Dashboard", "Home")
                    );

                //encrypt the ticket and add it to a cookie
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
                Response.Cookies.Add(cookie);
                var statistics = new SystemStatistic();
                if (restaurant != null)
                {
                    statistics.RestaurantId   = restaurant.RestaurantId;
                    statistics.Action         = StatisticsEnum.Login.ToString();
                    statistics.DateOccured    = DateTime.Now;
                    statistics.LoggedInUserId = appUser.AppUserId;

                    _db.SystemStatistics.Add(statistics);
                    _db.SaveChanges();
                    if ((restaurant.SetUpStatus == SetUpStatus.Incomplete.ToString() && userRole.Name == "Restaurant Administrator"))
                    {
                        return(RedirectToAction("Create", "RestaurantStructures"));
                    }
                }
                return(RedirectToAction("Dashboard", "Home"));
            }
            TempData["login"]            = "******";
            TempData["notificationType"] = NotificationType.Error.ToString();
            return(View(model));

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            //var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
            //switch (result)
            //{
            //    case SignInStatus.Success:
            //        return RedirectToLocal(returnUrl);
            //    case SignInStatus.LockedOut:
            //        return View("Lockout");
            //    case SignInStatus.RequiresVerification:
            //        return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            //    case SignInStatus.Failure:
            //    default:
            //        ModelState.AddModelError("", "Invalid login attempt.");
            //        return View(model);
            //}
        }