Exemplo n.º 1
0
        public static void SignOut(ISecurityService authenticationService)
        {
            var cookie = AuthCookie.GetCurrent();

            if (cookie != null)
            {
                if (!string.IsNullOrEmpty(cookie.SessionUid))
                {
                    HttpContext.Current.Cache.Remove(cookie.SessionUid);
                    //ICacheService cacheService = ((IContainer)System.Web.HttpContext.Current.Application["container"]).Resolve<ICacheService>();
                    //cacheService.Remove(string.Format("UserSessionID:{0}", cookie.SessionUid));
                    if (string.IsNullOrEmpty(cookie.Username))
                    {
                        authenticationService.SignOut(cookie.SessionUid);
                    }
                }

                cookie.SessionUid = null;
                cookie.Username   = null;
                cookie.UserRoles  = null;
                cookie.BranchCode = null;
                cookie.AuthExpiry = Helper.GetLocalDate().AddDays(-1);
                cookie.Delete();
            }

            //create a new anonymous identity/principal.
            var identity  = new System.Security.Principal.GenericIdentity("");
            var principal = new System.Security.Principal.GenericPrincipal(identity, null);

            //assign the anonymous principle to the context
            System.Web.HttpContext.Current.User      = principal;
            System.Threading.Thread.CurrentPrincipal = principal;
        }
Exemplo n.º 2
0
        //*********************************************************************
        ///
        /// <summary>
        ///
        /// </summary>
        /// <param name="credentials"></param>
        /// <returns></returns>
        ///
        //*********************************************************************

        private static bool AuthenticateUser(string credentials)
        {
            var validated = false;

            try
            {
                var encoding = System.Text.Encoding.GetEncoding("iso-8859-1");
                credentials = encoding.GetString(Convert.FromBase64String(credentials));

                var separator = credentials.IndexOf(':');
                var name      = credentials.Substring(0, separator);
                var password  = credentials.Substring(separator + 1);

                validated = IsAuthorized(name, password);

                if (validated)
                {
                    var identity = new System.Security.Principal.GenericIdentity(name);
                    SetPrincipal(new System.Security.Principal.GenericPrincipal(identity, null));
                }
            }
            catch (FormatException)
            {
                // Credentials were not formatted correctly.
                validated = false;
            }
            return(validated);
        }
Exemplo n.º 3
0
 public void SetCurrentUserFromIdentity()
 {
     // ユーザー情報
     // 企業ユーザーの場合は会社情報も取得
     var p = _context.User.Identity;
     if (p.IsAuthenticated)
     {
         using (var db = new Models.Entities())
         {
             db.Configuration.ProxyCreationEnabled = false;
             // TODO: UserNameの一意性保証
             this.CurrentUser = db.Users.FirstOrDefault(x => x.UserName == p.Name);
             var au = this.CurrentUser as Models.AccountUser;
             if (au != null)
             {
                 db.Entry(au).Reference(x => x.Company).Load();
             }
         }
     }
     if (this.CurrentUser == null)
     {
         // 未認証とする
         this.CurrentUser = Models.User.Anonymous;
         if (p.IsAuthenticated)
         {
             // 認証クッキーが有効だが、DBにユーザーが存在しない場合の対処
             var identity = new System.Security.Principal.GenericIdentity("");
             var principal = new System.Security.Principal.GenericPrincipal(identity, null);
             _context.User = principal;
         }
     }
 }
Exemplo n.º 4
0
        public static LoggedUserModel GetUser()
        {
            try
            {
                LoggedUserModel usr        = null;
                HttpCookie      authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
                if (authCookie != null)
                {
                    // Get the forms authentication ticket.
                    FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                    var identity = new System.Security.Principal.GenericIdentity(authTicket.Name, "Forms");
                    //var principal = new System.Security.Principal.IPrincipal(identity);

                    // Get the custom user data encrypted in the ticket.
                    string userData = ((FormsIdentity)(HttpContext.Current.User.Identity)).Ticket.UserData;

                    // Deserialize the json data and set it on the custom principal.
                    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                    usr = (LoggedUserModel)serializer.Deserialize(userData, typeof(LoggedUserModel));
                }
                return(usr);
            }
            catch (Exception ex)
            {
                //System.Web.HttpContext.Current.Response.Redirect(Tools.config.url + "admin/login/logoff");
                return(null);
            }
        }
Exemplo n.º 5
0
        public async Task <IActionResult> Register(UserIdentity model)
        {
            if (ModelState.IsValid)
            {
                System.Security.Principal.GenericIdentity identity = new System.Security.Principal.GenericIdentity(string.Empty);

                model.Id = Guid.NewGuid().ToString();
                //model.PasswordHash = model.Password.GetHashCode().ToString();

                var user = new UserIdentity
                {
                    UserName    = model.UserName,
                    Name        = model.Name,
                    Password    = model.Password,
                    Surname     = model.Surname,
                    PhoneNumber = model.PhoneNumber,
                    Email       = model.Email,
                    Id          = model.Id
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                user.SecurityStamp = Guid.NewGuid().ToString();
                await _signManager.PasswordSignInAsync(user, user.Password, true, true);

                //_context.Identities.Add(model);
                //_context.SaveChanges();
                return(View("/Views/Home/Index.cshtml"));
            }
            else
            {
                throw new Exception("Error registration");
            }
        }
Exemplo n.º 6
0
        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            //Is Authenticated?
            if (this.Context.Request.IsAuthenticated == false)
            {
                return;
            }

            //Get Current User
            string currentUsername = this.Context.User.Identity.Name;

            //GetUserManager
            UserManager userMgr = new UserManager();

            //Get USer from Manager
            User usr = userMgr.GetAllUsers().FirstOrDefault(row => row.UserName == currentUsername);

            //Get User_Roles from Manager
            IEnumerable <UserRole> allUsersRoles = userMgr.GetUserRoles(usr.Id);

            //Create Identity Object
            System.Security.Principal.GenericIdentity identity;
            identity = new System.Security.Principal.GenericIdentity(currentUsername);

            //Get Roles as an array of string
            string[] roles;
            roles = allUsersRoles.Select(ur => ur.Role.Name).ToArray();

            //Create Principal Object
            System.Security.Principal.GenericPrincipal principal;
            principal = new System.Security.Principal.GenericPrincipal(identity, roles);

            //Set Principal as new User
            this.Context.User = principal;
        }
Exemplo n.º 7
0
        public ActionResult ExternalSignOn(clientauth.SignOnJson model)
        {
            clientauth.UserInfo sgn = null;
            try
            {
                sgn = Newtonsoft.Json.JsonConvert.DeserializeObject <clientauth.UserInfo>(model.jsonstr);
            }
            catch { }
            if (sgn != null && (string.IsNullOrEmpty(sgn.login) == false))
            {
                {
                    System.Security.Principal.GenericIdentity newUser =
                        new System.Security.Principal.GenericIdentity(sgn.login);
                    System.Threading.Thread.CurrentPrincipal =
                        new System.Security.Principal.GenericPrincipal(newUser, clientauth.globals.brl);
                    if (System.Web.HttpContext.Current != null)
                    {
                        System.Web.HttpContext.Current.User =
                            System.Threading.Thread.CurrentPrincipal;
                    }
                }
                System.Web.Security.FormsAuthentication.SetAuthCookie(sgn.login, false);
            }

            return(Redirect("/"));
        }
Exemplo n.º 8
0
        public void SetCurrentUserFromIdentity()
        {
            // ユーザー情報
            // 企業ユーザーの場合は会社情報も取得
            var p = _context.User.Identity;

            if (p.IsAuthenticated)
            {
                using (var db = new Models.Entities())
                {
                    db.Configuration.ProxyCreationEnabled = false;
                    // TODO: UserNameの一意性保証
                    this.CurrentUser = db.Users.FirstOrDefault(x => x.UserName == p.Name);
                    var au = this.CurrentUser as Models.AccountUser;
                    if (au != null)
                    {
                        db.Entry(au).Reference(x => x.Company).Load();
                    }
                }
            }
            if (this.CurrentUser == null)
            {
                // 未認証とする
                this.CurrentUser = Models.User.Anonymous;
                if (p.IsAuthenticated)
                {
                    // 認証クッキーが有効だが、DBにユーザーが存在しない場合の対処
                    var identity  = new System.Security.Principal.GenericIdentity("");
                    var principal = new System.Security.Principal.GenericPrincipal(identity, null);
                    _context.User = principal;
                }
            }
        }
Exemplo n.º 9
0
        private void CreateauTicket(string loginRole)
        {
            try
            {
                WorkingProfile.UserRole         = loginRole;
                WorkingProfile.UserRoleLogin    = loginRole;
                WorkingProfile.ClientUserScreen = txtResolution.Value;

                Boolean iscookiepersistent           = chkPersist.Checked;
                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, txtUserName.Text.ToLower(), DateTime.Now, DateTime.Now.AddMinutes(60), iscookiepersistent, "");
                string     encryptedTitcket          = FormsAuthentication.Encrypt(authTicket);
                HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTitcket);
                if (iscookiepersistent)
                {
                    authCookie.Expires = authTicket.Expiration;
                }
                Response.Cookies.Add(authCookie);
                System.Security.Principal.GenericIdentity  id        = new System.Security.Principal.GenericIdentity(authTicket.Name, "LdapAuthentication");
                System.Security.Principal.GenericPrincipal principal = new System.Security.Principal.GenericPrincipal(id, null);
                FormsAuthentication.RedirectFromLoginPage(txtUserName.Text.ToLower(), chkPersist.Checked);
            }
            catch (Exception ex)
            {
                string exm = ex.Message;
            }
        }
Exemplo n.º 10
0
        public void Setup()
        {
            var config = new HttpConfiguration();

            config.Routes.MapHttpRoute(
                name: "Default",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional });

            _request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");
            _request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
            _request.Properties[HttpPropertyKeys.HttpRouteDataKey]     = new HttpRouteData(new HttpRoute());

            _mockContainer = new Data.Mocks.MockContainer();
            _teamRepo      = new Data.TeamRepo(_mockContainer);
            _goalRepo      = new Data.GoalRepo(_mockContainer);
            _dimensionRepo = new Data.DimensionRepo(_mockContainer);


            var identity = new System.Security.Principal.GenericIdentity("*****@*****.**");
            var princpal = new System.Security.Principal.GenericPrincipal(identity, new string[] { });

            _controller         = new GoalController(_goalRepo, _teamRepo, _dimensionRepo);
            _controller.User    = princpal;
            _controller.Request = _request;
        }
Exemplo n.º 11
0
        public void Setup()
        {
            var config = new HttpConfiguration();

            config.Routes.MapHttpRoute(
                name: "Default",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional });

            _request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");
            _request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
            _request.Properties[HttpPropertyKeys.HttpRouteDataKey] = new HttpRouteData(new HttpRoute());

            _mockContainer = new Data.Mocks.MockContainer();
            _teamRepo = new Data.TeamRepo(_mockContainer);
            _goalRepo = new Data.GoalRepo(_mockContainer);
            _dimensionRepo = new Data.DimensionRepo(_mockContainer);

            var identity = new System.Security.Principal.GenericIdentity("*****@*****.**");
            var princpal = new System.Security.Principal.GenericPrincipal(identity, new string[] { });

            _controller = new GoalController(_goalRepo, _teamRepo, _dimensionRepo);
            _controller.User = princpal;
            _controller.Request = _request;
        }
Exemplo n.º 12
0
        public void TestThatUserWhoCreatesTeamIsSetAsTeamAdmin()
        {
            /// var user = System.Security.Principal.WindowsIdentity.GetCurrent();

            var identity = new System.Security.Principal.GenericIdentity("TestUser");
            var princpal = new System.Security.Principal.GenericPrincipal(identity, new string[] { });

            TeamController.CurrentUser = princpal;
            TeamController teamController = CreateTeamController();

            teamController.Request = _request;
            teamController.User    = princpal;

            Core.Models.Team newTeam = new Core.Models.Team()
            {
                Name = Guid.NewGuid().ToString()
            };

            var result = teamController.Post(newTeam);

            var team = _mockContainer.Teams.Where(i => i.Name == newTeam.Name).FirstOrDefault();

            Assert.IsNotNull(team, "Could not find new team");

            var teamMember = team.TeamMembers.Where(i => i.UserId == identity.Name).FirstOrDefault();

            string allUsers = String.Join(",", team.TeamMembers.Select(i => i.UserId + i.IsAdmin.ToString()).ToArray());


            Assert.IsNotNull(teamMember, "User was not assigned to team. The current user is " + identity.Name + " Current Users:" + allUsers);

            Assert.IsTrue(teamMember.IsAdmin, "User was not created as administrator.");
        }
Exemplo n.º 13
0
        public void TestThatTeamWithNoAssessmentResultsGetsDefaultRating()
        {
            CreateTeamWithMember();

            var assessmentResults = new List <Continuum.Data.AssessmentResult>();

            _mockContainer.Assessments.Add(new Data.Assessment()
            {
                DateCreated       = DateTime.Now,
                AssessmentResults = assessmentResults,
                Status            = new Data.AssessmentStatus()
                {
                    Value = "Closed"
                }
            });

            var identity  = new System.Security.Principal.GenericIdentity("TestUser");
            var principal = new System.Security.Principal.GenericPrincipal(identity, new string[] { });

            Continuum.WebApi.Logic.AssessmentLogic assessmentLogic = new WebApi.Logic.AssessmentLogic(_assessmentRepo, _teamRepository, _dimensionRepo, principal);

            int rating = assessmentLogic.GetCurrentLevelForTeam();

            Assert.IsTrue(rating == 1, "Rating must be 1 if there is not assessment info.");
        }
Exemplo n.º 14
0
        /// <summary>
        /// Implement logic for AuthenticateUser
        /// </summary>
        /// <param name="credentials"></param>
        /// <createdby>Bobi</createdby>
        /// <createddate>28 Feb 2015</createddate>
        private static void AuthenticateUser(string credentials)
        {
            try
            {
                //Encode the passed credentials with request
                var encoding = Encoding.GetEncoding("iso-8859-1");
                credentials = encoding.GetString(Convert.FromBase64String(credentials));

                //get the passed user name and password
                int    separator = credentials.IndexOf(':');
                string name      = credentials.Substring(0, separator);
                string password  = credentials.Substring(separator + 1);
                //check that username and password which we get from current request is correct or not
                if (CheckPassword(name, password))
                {
                    var identity = new System.Security.Principal.GenericIdentity(name);
                    SetPrincipal(new System.Security.Principal.GenericPrincipal(identity, null));
                }
                else
                {
                    //Invalid username or password.
                    HttpContext.Current.Response.StatusCode = 401;
                }
            }
            catch (FormatException)
            {
                // Credentials were not formatted correctly.
                HttpContext.Current.Response.StatusCode = 401;
            }
        }
        public async Task <IActionResult> Login([FromBody] AuthenticationModel model)
        {
            if (!this.ModelState.IsValid)
            {
                return(Unauthorized());
            }

            var faceStream = new MemoryStream(Convert.FromBase64String(model.Face));

            if (await _identityService.Authenticate(model.Email, faceStream))
            {
                var userIdentity    = new System.Security.Principal.GenericIdentity(model.Email, "Biometric");
                var claimsPrincipal = new ClaimsPrincipal(userIdentity);
                await this.HttpContext.SignInAsync(AUTHENTICATION_SCHEME,
                                                   claimsPrincipal,
                                                   new AuthenticationProperties
                {
                    IsPersistent = true
                });

                return(Ok());
            }
            else
            {
                return(Unauthorized());
            }
        }
Exemplo n.º 16
0
        public InversionsController_Select_Test()
        {
            _contextOptions = CreateNewContextOptions();
            context         = new ApplicationDbContext(_contextOptions);

            // Insert seed data into the database using one instance of the context

            //Areas Temáticas
            context.Areas.Add(new Areas {
                Nombre = "Sanidad"
            });

            //Rating
            var rating = new Rating {
                Nombre = "A"
            };

            context.Rating.Add(rating);

            //Tipos de Inversiones
            context.TiposInversiones.Add(new TiposInversiones {
                Nombre = "Crowdfunding"
            });

            //Proyecto
            context.Proyecto.Add(new Proyecto {
                ProyectoId = 1, FechaExpiracion = new DateTime(2019, 01, 23), Importe = 30000, Interes = (float)5.90, MinInversion = 50, Nombre = "E-MEDICA", NumInversores = 0, Plazo = 12, Progreso = 0, Rating = rating
            });
            context.Proyecto.Add(new Proyecto {
                ProyectoId = 2, FechaExpiracion = new DateTime(2019, 01, 14), Importe = 70000, Interes = (float)7.25, MinInversion = 0, Nombre = "PROTOS", NumInversores = 0, Plazo = 48, Progreso = 0, Rating = rating
            });
            //context.Proyecto.Add (new Proyecto { ProyectoId = 3, FechaExpiracion = new DateTime (2019, 01, 14), Importe = 93000, Interes = (float) 4.50, MinInversion = 100, Nombre = "SUBSOLE", NumInversores = 0, Plazo = 6, Progreso = 0, RatingId = 1 });

            //Inversor
            context.Users.Add(new Inversor {
                UserName         = "******", NIF = "47446245M", PhoneNumber = "684010548", Email = "*****@*****.**",
                Nombre           = "Yasin", Apellido1 = "Muñoz", Apellido2 = "El Merabety", Domicilio = "Gabriel Ciscar, 26", Nacionalidad = "Española",
                PaisDeResidencia = "España", Provincia = "Albacete"
            });

            context.SaveChanges();

            foreach (var proyecto in context.Proyecto.ToList())
            {
                context.ProyectoAreas.Add(new ProyectoAreas {
                    Proyecto = proyecto, Areas = context.Areas.First()
                });
                context.ProyectoTiposInversiones.Add(new ProyectoTiposInversiones {
                    Proyecto = proyecto, TiposInversiones = context.TiposInversiones.First()
                });
            }
            context.SaveChanges();

            //Simulación conexión de un usuario
            System.Security.Principal.GenericIdentity user     = new System.Security.Principal.GenericIdentity("*****@*****.**");
            System.Security.Claims.ClaimsPrincipal    identity = new System.Security.Claims.ClaimsPrincipal(user);
            inversionContext      = new Microsoft.AspNetCore.Http.DefaultHttpContext();
            inversionContext.User = identity;
        }
Exemplo n.º 17
0
        private WebApi.Logic.TeamLogic CreateTeamLogic(string[] roles)
        {
            var identity  = new System.Security.Principal.GenericIdentity("TestUser");
            var principal = new System.Security.Principal.GenericPrincipal(identity, roles);
            var teamLogic = new WebApi.Logic.TeamLogic(_teamRepository, principal);

            return(teamLogic);
        }
        public void RunBeforeEachTest()
        {
            System.Security.Principal.GenericIdentity identity = new System.Security.Principal.GenericIdentity("unittest\\user", "UnitTestAuth");

            System.Security.Principal.GenericPrincipal gp = new System.Security.Principal.GenericPrincipal(identity, new string[] { "FirstRole", "ThirdRole" });

            System.Threading.Thread.CurrentPrincipal = gp;
        }
Exemplo n.º 19
0
 public void SerializeCslaClaimsPrincipal()
 {
   var identity = new System.Security.Principal.GenericIdentity("rocky", "custom");
   var principal = new Csla.Security.CslaClaimsPrincipal(identity);
   var clone = (Csla.Security.CslaClaimsPrincipal)Core.ObjectCloner.Clone(principal);
   Assert.AreEqual(principal.Identity.Name, clone.Identity.Name);
   Assert.AreEqual(principal.Identity.AuthenticationType, clone.Identity.AuthenticationType);
 }
Exemplo n.º 20
0
        public void SetThreadPrincipal()
        {
            Assert.Throws <ArgumentNullException>(() => { AppDomain.CurrentDomain.SetThreadPrincipal(null); });
            var identity  = new System.Security.Principal.GenericIdentity("NewUser");
            var principal = new System.Security.Principal.GenericPrincipal(identity, null);

            AppDomain.CurrentDomain.SetThreadPrincipal(principal);
        }
Exemplo n.º 21
0
        public async Task <ClaimsIdentity> CreateIdentityAsync(ApplicationUser user, string applicationCookie)
        {
            var t  = new System.Security.Principal.GenericIdentity(user.UserName, applicationCookie);
            var c2 = new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", user.Id + "");
            var c1 = new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity");

            return(new ClaimsIdentity(t, new[] { c1, c2 }));
        }
Exemplo n.º 22
0
        private WebApi.Logic.AssessmentLogic CreateAssessmentLogic()
        {
            var identity  = new System.Security.Principal.GenericIdentity("TestUser");
            var principal = new System.Security.Principal.GenericPrincipal(identity, new string[] { });

            Continuum.WebApi.Logic.AssessmentLogic assessmentLogic = new WebApi.Logic.AssessmentLogic(_assessmentRepo, _teamRepository, _dimensionRepo, principal);
            return(assessmentLogic);
        }
Exemplo n.º 23
0
        public ActionResult Post(LoginModel login)
        {
            // Add JWT generation endpoint:
            var keyByteArray = Encoding.ASCII.GetBytes(secretKey);
            var signingKey   = new SymmetricSecurityKey(keyByteArray);
            var options      = new TokenProviderOptionsModel
            {
                Audience           = "DropTheMic",
                Issuer             = "DropTheMicCore",
                SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
            };
            ClaimsIdentity claim;

            if (!string.IsNullOrEmpty(login.username) && !string.IsNullOrEmpty(login.password))
            {
                //if (user == null)
                //{
                //	return NotFound();
                //}

                System.Security.Principal.GenericIdentity identity = new System.Security.Principal.GenericIdentity(login.username, "Token");

                claim = new ClaimsIdentity(identity, new Claim[] { });
            }
            else
            {
                return(NotFound());
            }

            var now = DateTime.UtcNow;

            // Specifically add the jti (random nonce), iat (issued timestamp), and sub (subject/user) claims.
            // You can add other claims here, if you want:
            var claims = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, login.username),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Iat, now.Second.ToString(), ClaimValueTypes.Integer64),
                new Claim("idUser", "111"),
            };

            // Create the JWT and write it to a string
            var jwt = new JwtSecurityToken(
                issuer: options.Issuer,
                audience: options.Audience,
                claims: claims,
                notBefore: now,
                expires: now.Add(options.Expiration),
                signingCredentials: options.SigningCredentials);
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            return(Ok(new
            {
                access_token = encodedJwt,
                expires_in = (int)options.Expiration.TotalSeconds
            }));
        }
Exemplo n.º 24
0
        private Task <ClaimsIdentity> GetIdentity(string userId, string userName, string userType, string[] roleClaims)
        {
            var identity = new System.Security.Principal.GenericIdentity(userId, "Token");
            var claims   = roleClaims.Select(rc => new Claim(identity.RoleClaimType, rc)).ToList();

            claims.Add(new Claim("PEngineUserName", userName));
            claims.Add(new Claim("PEngineUserType", userType));
            return(Task.FromResult(new ClaimsIdentity(identity, claims)));
        }
Exemplo n.º 25
0
 public void SetThreadPrincipal()
 {
     RemoteInvoke(() => {
         Assert.Throws <ArgumentNullException>(() => { AppDomain.CurrentDomain.SetThreadPrincipal(null); });
         var identity  = new System.Security.Principal.GenericIdentity("NewUser");
         var principal = new System.Security.Principal.GenericPrincipal(identity, null);
         AppDomain.CurrentDomain.SetThreadPrincipal(principal);
         return(SuccessExitCode);
     }).Dispose();
 }
        public void TestThatAttemptingToAccessAssessmentWithoutTeamThrowsException()
        {
            var identity = new System.Security.Principal.GenericIdentity("*****@*****.**");
            var princpal = new System.Security.Principal.GenericPrincipal(identity, new string[] { });

            Continuum.WebApi.Controllers.AssessmentController.CurrentUser = princpal;

            _assessmentController.User = princpal;

            _assessmentController.Get();
        }
        public void SerializeCslaClaimsPrincipal()
        {
            var identity           = new System.Security.Principal.GenericIdentity("rocky", "custom");
            var principal          = new Csla.Security.CslaClaimsPrincipal(identity);
            var applicationContext = _testDIContext.CreateTestApplicationContext();
            var cloner             = new Core.ObjectCloner(applicationContext);
            var clone = (Csla.Security.CslaClaimsPrincipal)cloner.Clone(principal);

            Assert.AreEqual(principal.Identity.Name, clone.Identity.Name);
            Assert.AreEqual(principal.Identity.AuthenticationType, clone.Identity.AuthenticationType);
        }
Exemplo n.º 28
0
        public void TestThatAttemptingToAccessAssessmentWithoutTeamThrowsException()
        {
            var identity = new System.Security.Principal.GenericIdentity("*****@*****.**");
            var princpal = new System.Security.Principal.GenericPrincipal(identity, new string[] { });

            Continuum.WebApi.Controllers.AssessmentController.CurrentUser = princpal;

            _assessmentController.User = princpal;

            _assessmentController.Get();
        }
Exemplo n.º 29
0
        public void Setup()
        {
            _mockContainer = new Data.Mocks.MockContainer();
            _teamRepo = new Continuum.Data.TeamRepo(_mockContainer);

            var identity = new System.Security.Principal.GenericIdentity("*****@*****.**");
            _currentUser = new System.Security.Principal.GenericPrincipal(identity, new string[] { });

            WebApi.Controllers.UserController.CurrentUser = _currentUser;

            _controller = new WebApi.Controllers.UserController(_teamRepo);
            _controller.User = _currentUser;
        }
Exemplo n.º 30
0
        public void TestThatTeamWithNoAssessmentsHasDefaultRating()
        {
            CreateTeamWithMember();

            var identity  = new System.Security.Principal.GenericIdentity("TestUser");
            var principal = new System.Security.Principal.GenericPrincipal(identity, new string[] { });

            Continuum.WebApi.Logic.AssessmentLogic assessmentLogic = new WebApi.Logic.AssessmentLogic(_assessmentRepo, _teamRepository, _dimensionRepo, principal);

            int rating = assessmentLogic.GetCurrentLevelForTeam();

            Assert.IsTrue(rating == 1, "Rating must be 1 if there is not assessment info.");
        }
Exemplo n.º 31
0
        public static string SetCurrentUser(string username)
        {
            string errorMessage = string.Empty;

            // Initialize FormsAuthentication, for what it's worth.
            FormsAuthentication.Initialize();
            MembershipUser user = Membership.GetUser(username, true);

            if (user == null)
            {
                errorMessage = "Employee '" + username + "' was not found.";
            }
            if (String.IsNullOrEmpty(errorMessage))
            {
                string[] roles       = System.Web.Security.Roles.GetRolesForUser(username);
                string   rolesString = string.Empty;
                for (int i = 0; i < roles.Length; i++)
                {
                    if (i > 0)
                    {
                        rolesString += ",";
                    }
                    rolesString += roles[i];
                }
                // Create a new ticket used for authentication. Ticket lasts 30 min by default.
                double loginRememberMinutes = 30;
                if (SecurityContext.Current.CookieRememberMe)
                {
                    loginRememberMinutes = SecurityContext.Current.LoginRememberMinutes;
                }

                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddMinutes(loginRememberMinutes), true, rolesString, FormsAuthentication.FormsCookiePath);
                // Encrypt the cookie using the machine key for secure transport.
                string     hash   = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);                 // Hashed ticket
                // Set the cookie's expiration time to the tickets expiration time
                if (ticket.IsPersistent)
                {
                    cookie.Expires = ticket.Expiration;
                }
                System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
                // Create Identity.
                System.Security.Principal.GenericIdentity identity = new System.Security.Principal.GenericIdentity(user.UserName);
                // Create Principal.
                RolePrincipal principal = new RolePrincipal(identity);
                System.Threading.Thread.CurrentPrincipal = principal;
                // Create User.
                HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(identity, roles);
            }
            return(errorMessage);
        }
Exemplo n.º 32
0
 /// <summary>
 /// Sets the auth ticket.
 /// </summary>
 /// <param name="user">The user.</param>
 /// <param name="context">The context.</param>
 public static void SetAuthTicket(User user, HttpContextBase context)
 {
     var id = new System.Security.Principal.GenericIdentity(user.UserName);
     var tempUser = GetPrincipal(user);
     var serializer = new JavaScriptSerializer();
     var userData = serializer.Serialize(user);
     var authTicket = new FormsAuthenticationTicket(
         1, user.UserName,
         DateTime.Now, DateTime.Now.AddMinutes(30),
         false, userData);
     var ticket = FormsAuthentication.Encrypt(authTicket);
     var faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticket);
     context.Response.Cookies.Add(faCookie);
 }
Exemplo n.º 33
0
        protected override Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            Task <AuthenticateResult> rtnTask = Task <AuthenticateResult> .Factory.StartNew(() =>
            {
                NoAuthIdentity noauthIdentity                = new NoAuthIdentity();
                System.Security.Claims.ClaimsIdentity ci     = new System.Security.Claims.ClaimsIdentity();
                System.Security.Principal.GenericIdentity gi = new System.Security.Principal.GenericIdentity("NoUser");
                System.Security.Claims.ClaimsPrincipal p     = new System.Security.Claims.ClaimsPrincipal(noauthIdentity);
                AuthenticationTicket ticket = new AuthenticationTicket(p, "NoAuthScheme");
                return(AuthenticateResult.Success(ticket));
            });

            return(rtnTask);
        }
Exemplo n.º 34
0
 protected void Application_AuthenticateRequest(Object sender, EventArgs e)
 {
     var cookieName = System.Web.Security.FormsAuthentication.FormsCookieName;
     var authCookie = this.Context.Request.Cookies[cookieName];
     if (authCookie != null) {
         var authTicket = System.Web.Security.FormsAuthentication.Decrypt(authCookie.Value);
         if (authTicket != null) {
             var groups = authTicket.UserData.Split('|');
             var id = new System.Security.Principal.GenericIdentity(authTicket.Name, "LdapAuthentication");
             var principal = new System.Security.Principal.GenericPrincipal(id, groups);
             this.Context.User = principal;
         }
     }
 }
Exemplo n.º 35
0
        private AuthorizationHandlerContext CreateAuthContext(string scopeClaimKey, IEnumerable <IAuthorizationRequirement> requirements, IEnumerable <string> userScopes)
        {
            var identity = new System.Security.Principal.GenericIdentity("Me");

            foreach (var scope in userScopes)
            {
                identity.AddClaim(new System.Security.Claims.Claim(scopeClaimKey, scope));
            }

            var principal = new System.Security.Principal.GenericPrincipal(identity, Array.Empty <string>());
            var context   = new AuthorizationHandlerContext(requirements, principal, null);

            return(context);
        }
        public void Setup()
        {
            _mockContainer = new Data.Mocks.MockContainer();
            _assessmentRepo = new Continuum.Data.AssessmentRepo(_mockContainer);
            _teamRepo = new Continuum.Data.TeamRepo(_mockContainer);
            _dimensionRepo = new Data.DimensionRepo(_mockContainer);

            var identity = new System.Security.Principal.GenericIdentity("*****@*****.**");
            var princpal = new System.Security.Principal.GenericPrincipal(identity, new string[] { });
            Continuum.WebApi.Controllers.AssessmentController.CurrentUser = princpal;

            _assessmentController = new Continuum.WebApi.Controllers.AssessmentController(_assessmentRepo, _teamRepo, _dimensionRepo);
            _assessmentController.User = princpal;
        }
Exemplo n.º 37
0
        /// <summary>
        /// Check if the current user principal has access to the requested resource.
        /// </summary>
        /// <returns>Returns True if the current user has access to the requested resource, otherwise False</returns>
        internal static bool CheckUrlAccessForCurrentPrincipal()
        {
            HttpContext context = HttpContext.Current;
            HttpRequest request = context.Request;
            var         user    = context.User;

            if (user == null)
            {
                var identity = new System.Security.Principal.GenericIdentity("", "");
                user = new System.Security.Principal.GenericPrincipal(identity, new string[] { });
            }

            return(System.Web.Security.UrlAuthorizationModule.CheckUrlAccessForPrincipal(request.Path, user, request.HttpMethod));
        }
Exemplo n.º 38
0
        //针对所有请求,就会到这里
        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            HttpRequest request = HttpContext.Current.Request;

            //找请求的cookie里面是否有用户票据
            HttpCookie cookie = request.Cookies["Ticket"];

            string name = string.Empty;

            if (cookie != null)
            {
                string ticketstring = cookie.Value;

                //解密

                System.Web.Security.FormsAuthenticationTicket ticket
                    = System.Web.Security.FormsAuthentication.Decrypt(ticketstring);

                name = ticket.Name;


            }

            //上面是教学实践,下面是微软写好的
            //MyIdentity identity = new MyIdentity(name, "Type");
            System.Security.Principal.GenericIdentity identity
                = new System.Security.Principal.GenericIdentity(name, "Type");

            //MyPrinciple user = new MyPrinciple(identity, new string[] { });
            System.Security.Principal.GenericPrincipal user
                = new System.Security.Principal.GenericPrincipal(identity,new string[] { } );

            HttpContext context = HttpContext.Current;
            context.Items.Add("User", user);


        }
Exemplo n.º 39
0
        /// <summary>
        /// Check if the current user principal has access to the requested resource.
        /// </summary>
        /// <returns>Returns True if the current user has access to the requested resource, otherwise False</returns>
        internal static bool CheckUrlAccessForCurrentPrincipal()
        {
            HttpContext context = HttpContext.Current;
            HttpRequest request = context.Request;
            var user = context.User;

            if (user == null)
            {
                var identity = new System.Security.Principal.GenericIdentity("", "");
                user = new System.Security.Principal.GenericPrincipal(identity, new string[] { });
            }

            return System.Web.Security.UrlAuthorizationModule.CheckUrlAccessForPrincipal(request.Path, user, request.HttpMethod);
        }
Exemplo n.º 40
0
 public KeyValueList SignIn(string username, string password)
 {
     string errorMessage = string.Empty;
     if (password.Length == 0) errorMessage = "Please enter password";
     if (username.Length == 0) errorMessage = "Please enter user name";
     if (errorMessage.Length == 0)
     {
         // Here must be validation with password. You can add third party validation here;
         bool success = Membership.ValidateUser(username, password);
         if (!success) errorMessage = "Validation failed. User name '" + username + "' was not found.";
     }
     var results = new KeyValueList();
     if (errorMessage.Length > 0)
     {
         results.Add("Status", false);
         results.Add("Message", errorMessage);
     }
     else
     {
         FormsAuthentication.Initialize();
         var user = Membership.GetUser(username, true);
         if (user == null)
         {
             results.Add("Status", false);
             results.Add("Message", "'" + username + "' was not found.");
         }
         else
         {
             var roles = Roles.GetRolesForUser(username);
             string rolesString = string.Empty;
             for (int i = 0; i < roles.Length; i++)
             {
                 if (i > 0) rolesString += ",";
                 rolesString += roles[i];
             }
             var loginRememberMinutes = 30;
             var ticket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddMinutes(loginRememberMinutes), true, rolesString, FormsAuthentication.FormsCookiePath);
             // Encrypt the cookie using the machine key for secure transport.
             var hash = FormsAuthentication.Encrypt(ticket);
             var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash); // Hashed ticket
             // Set the cookie's expiration time to the tickets expiration time
             if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
             HttpContext.Current.Response.Cookies.Add(cookie);
             // Create Identity.
             var identity = new System.Security.Principal.GenericIdentity(user.UserName);
             // Create Principal.
             var principal = new RolePrincipal(identity);
             System.Threading.Thread.CurrentPrincipal = principal;
             // Create User.
             HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(identity, roles);
             results.Add("Status", true);
             results.Add("Message", "Welcome!");
         }
     }
     return results;
 }
Exemplo n.º 41
0
        public void TestThatTeamWithNoAssessmentResultsGetsDefaultRating()
        {
            CreateTeamWithMember();

            var assessmentResults = new List<Continuum.Data.AssessmentResult>();

            _mockContainer.Assessments.Add(new Data.Assessment()
            {
                DateCreated = DateTime.Now,
                AssessmentResults = assessmentResults,
                Status = new Data.AssessmentStatus() { Value = "Closed" }
            });

            var identity = new System.Security.Principal.GenericIdentity("TestUser");
            var principal = new System.Security.Principal.GenericPrincipal(identity, new string[] { });

            Continuum.WebApi.Logic.AssessmentLogic assessmentLogic = new WebApi.Logic.AssessmentLogic(_assessmentRepo, _teamRepository, _dimensionRepo, principal);

            int rating = assessmentLogic.GetCurrentLevelForTeam();

            Assert.IsTrue(rating == 1, "Rating must be 1 if there is not assessment info.");
        }
Exemplo n.º 42
0
        public void TestThatTeamWithNoAssessmentsHasDefaultRating()
        {
            CreateTeamWithMember();

               var identity = new System.Security.Principal.GenericIdentity("TestUser");
               var principal = new System.Security.Principal.GenericPrincipal(identity, new string[] { });

               Continuum.WebApi.Logic.AssessmentLogic assessmentLogic = new WebApi.Logic.AssessmentLogic(_assessmentRepo, _teamRepository, _dimensionRepo, principal);

               int rating = assessmentLogic.GetCurrentLevelForTeam();

               Assert.IsTrue(rating == 1, "Rating must be 1 if there is not assessment info.");
        }
Exemplo n.º 43
0
        public void TestThatUserWhoCreatesTeamIsSetAsTeamAdmin()
        {
            /// var user = System.Security.Principal.WindowsIdentity.GetCurrent();

               var identity = new System.Security.Principal.GenericIdentity("TestUser");
               var princpal = new System.Security.Principal.GenericPrincipal(identity, new string[] { });

               TeamController.CurrentUser = princpal;
               TeamController teamController = CreateTeamController();
               teamController.Request = _request;
               teamController.User = princpal;

            Core.Models.Team newTeam = new Core.Models.Team()
            {
                Name = Guid.NewGuid().ToString()
            };

            var result = teamController.Post(newTeam);

            var team = _mockContainer.Teams.Where(i => i.Name == newTeam.Name).FirstOrDefault();
            Assert.IsNotNull(team, "Could not find new team");

            var teamMember = team.TeamMembers.Where(i => i.UserId == identity.Name).FirstOrDefault();

            string allUsers = String.Join(",",team.TeamMembers.Select(i => i.UserId + i.IsAdmin.ToString()).ToArray());

            Assert.IsNotNull(teamMember, "User was not assigned to team. The current user is " + identity.Name + " Current Users:" + allUsers);

            Assert.IsTrue(teamMember.IsAdmin, "User was not created as administrator.");
        }
Exemplo n.º 44
0
        private WebApi.Logic.AssessmentLogic CreateAssessmentLogic()
        {
            var identity = new System.Security.Principal.GenericIdentity("TestUser");
            var principal = new System.Security.Principal.GenericPrincipal(identity, new string[] { });

            Continuum.WebApi.Logic.AssessmentLogic assessmentLogic = new WebApi.Logic.AssessmentLogic(_assessmentRepo, _teamRepository, _dimensionRepo, principal);
            return assessmentLogic;
        }
Exemplo n.º 45
0
        public async Task<ClaimsIdentity> CreateIdentityAsync(ApplicationUser user, string applicationCookie)
        {
            var t = new System.Security.Principal.GenericIdentity(user.UserName, applicationCookie);
            var c2 = new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", user.Id + "");
            var c1 = new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity");

            return new ClaimsIdentity(t, new[] { c1, c2 });
        }
Exemplo n.º 46
0
        public static void SetAuthenticatedTicket(System.Guid userID, List<string> roleNames, bool createPersistentCookie)
        {
            // Ϊ������ userName��createPersistentCookie �� strCookiePath ���������֤Ʊ�������丽�ӵ� Cookie �������Ӧ���ϡ�����ִ���ض���

            string logonID = userID.ToString();
            System.Web.Security.FormsAuthentication.SetAuthCookie(logonID, createPersistentCookie);
            HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now.AddDays(1);

            string userData = "";
            for(int index = 0;index < roleNames.Count;index++)
            {
                userData += roleNames[index];

                if(index < roleNames.Count -1)userData += ",";
            }

            FormsAuthenticationTicket authTicket = new
                FormsAuthenticationTicket(
                1, // version
                logonID, // �û����
                DateTime.Now, // creation
                DateTime.Now.AddMinutes(20),// Expiration
                false, // Persistent
                userData); // User data

            string encryptedTicket = FormsAuthentication.Encrypt(authTicket); //����

            //����Cookie
            HttpCookie authCookie =
                               new HttpCookie(FormsAuthentication.FormsCookieName,
                               encryptedTicket);

            HttpContext.Current.Response.Cookies.Add(authCookie);

            // ���µ�ǰUser
            System.Security.Principal.GenericIdentity genericIdentity = new System.Security.Principal.GenericIdentity(logonID);
            System.Security.Principal.GenericPrincipal genericPrincipal = new System.Security.Principal.GenericPrincipal(genericIdentity, roleNames.ToArray());
            HttpContext.Current.User = genericPrincipal;
        }
Exemplo n.º 47
0
 public void SetThreadPrincipal()
 {
     Assert.Throws<ArgumentNullException>(() => {AppDomain.CurrentDomain.SetThreadPrincipal(null);});
     var identity = new System.Security.Principal.GenericIdentity("NewUser");
     var principal = new System.Security.Principal.GenericPrincipal(identity, null);
     AppDomain.CurrentDomain.SetThreadPrincipal(principal);
 }
Exemplo n.º 48
0
        protected void btnLogin_Click(object sender, System.EventArgs e)
        {
            string hash = AutoAssess.Misc.Hashing.GetMd5Hash(txtPassword.Text, "sadf");

            WebUser user = this.CurrentWebSession.CreateCriteria<WebUser> ()
                .Add (Restrictions.Eq ("Username", txtUsername.Text))
                .Add (Restrictions.Eq ("PasswordHash", hash))
                .Add (Restrictions.Eq ("IsActive", true))
                .List<WebUser>()
                .FirstOrDefault();

            if (user == null)
            {
                lblLoginError.Text = "Invalid username/password combination.";
                txtUsername.Text = string.Empty;
                txtPassword.Text = string.Empty;
                return;
            }

            VerificationKey key = this.CurrentWebSession.CreateCriteria<VerificationKey>()
                .Add (Restrictions.Eq ("WebUserID", user.ID))
                .UniqueResult<VerificationKey>();

            if (!key.IsVerifed)
            {
                lblLoginError.Text = "Please check your email for an account verification link.";
                txtUsername.Text = string.Empty;
                txtPassword.Text = string.Empty;
                return;
            }

            WebUserInfo info = this.CurrentWebSession.CreateCriteria<WebUserInfo>()
                .Add(Restrictions.Eq("WebUserID", user.ID))
                .UniqueResult<WebUserInfo>();

            info.LastLogin = DateTime.Now;

            using (ITransaction x = this.CurrentWebSession.BeginTransaction())
            {
                this.CurrentWebSession.SaveOrUpdate(info);

                try{
                    x.Commit();
                }
                catch(Exception ex)
                {
                    x.Rollback();
                    throw ex;
                }
            }

            Session["User"] = user;

            FormsAuthenticationTicket tkt = new FormsAuthenticationTicket (1, user.UserID.ToString(), DateTime.Now, DateTime.Now.AddMinutes (30), false, string.Empty /*Whatever data you want*/);
            string cookiestr = FormsAuthentication.Encrypt (tkt);
            HttpCookie ck = new HttpCookie (FormsAuthentication.FormsCookieName, cookiestr);

            ck.Path = FormsAuthentication.FormsCookiePath;
            Response.Cookies.Add (ck);

            Response.Redirect ("/Default.aspx", true);

            System.Security.Principal.GenericIdentity i = new System.Security.Principal.GenericIdentity(string.Empty, null);

            this.Context.User = new System.Security.Principal.GenericPrincipal(i, null);
        }
Exemplo n.º 49
0
 private WebApi.Logic.TeamLogic CreateTeamLogic(string[] roles)
 {
     var identity = new System.Security.Principal.GenericIdentity("TestUser");
     var principal = new System.Security.Principal.GenericPrincipal(identity, roles);
     var teamLogic = new WebApi.Logic.TeamLogic(_teamRepository, principal);
     return teamLogic;
 }
Exemplo n.º 50
0
        public static string SetCurrentUser(string username)
        {
            string errorMessage = string.Empty;
            // Initialize FormsAuthentication, for what it's worth.
            FormsAuthentication.Initialize();
            MembershipUser user = Membership.GetUser(username, true);
            if (user == null) errorMessage = "Employee '"+username+"' was not found.";
            if (String.IsNullOrEmpty(errorMessage))
            {
                string[] roles = System.Web.Security.Roles.GetRolesForUser(username);
                string rolesString = string.Empty;
                for (int i = 0; i < roles.Length; i++)
                {
                    if (i > 0) rolesString += ",";
                    rolesString += roles[i];
                }
                // Create a new ticket used for authentication. Ticket lasts 30 min by default.
                double loginRememberMinutes = 30;
                if (SecurityContext.Current.CookieRememberMe)
                {
                    loginRememberMinutes = SecurityContext.Current.LoginRememberMinutes;
                }

                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddMinutes(loginRememberMinutes), true, rolesString, FormsAuthentication.FormsCookiePath);
                // Encrypt the cookie using the machine key for secure transport.
                string hash = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash); // Hashed ticket
                // Set the cookie's expiration time to the tickets expiration time
                if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
                System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
                // Create Identity.
                System.Security.Principal.GenericIdentity identity = new System.Security.Principal.GenericIdentity(user.UserName);
                // Create Principal.
                RolePrincipal principal = new RolePrincipal(identity);
                System.Threading.Thread.CurrentPrincipal = principal;
                // Create User.
                HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(identity, roles);
            }
            return errorMessage;
        }