示例#1
0
        private CustomUser GetAutoCreateUser()
        {
            CustomUser usr = new CustomUser();

            usr.UserName = windowsUserName;
            //passwords will never get used for a windows auth user, so this is mostly just gibberish, but added so that i don't have to allow nulls for passwords in the database
            //extra amount of gibberish to potentially avoid a security issue
            usr.PasswordIterationCount = CustomEncrypt.minimumIterationCount;
            usr.PasswordSalt           = CustomEncrypt.PBKDF2GetRandomSalt();
            usr.PasswordHash           = CustomEncrypt.PBKDF2HashedPassword(windowsAuthPassword, usr.PasswordSalt, usr.PasswordIterationCount);
            //***************************************************************
            usr.IsUserAutoGenerated = true;
            usr.DateCreated         = System.DateTime.UtcNow;
            usr.DateLastModified    = System.DateTime.UtcNow;

            //this section is intended on connecting to the domain controller and getting some information about the user to add to our user object
            //doesn't always work based on the security of the DC.  based this attempt on https://stackoverflow.com/questions/20156913/get-active-directory-user-information-with-windows-authentication-in-mvc-4
            PrincipalContext ctx = null;

            try
            {
                ctx = new PrincipalContext(ContextType.Domain);
                UserPrincipalExtended windowsUser = UserPrincipalExtended.FindByIdentity(ctx, User.Identity.Name);
                if (windowsUser != null)
                {
                    usr.LastName  = windowsUser.Surname;
                    usr.FirstName = windowsUser.GivenName;
                    //windowsUser.Title;
                    //windowsUser.Department;

                    usr.PhoneNumber = windowsUser.VoiceTelephoneNumber;
                    usr.Email       = windowsUser.EmailAddress;
                }
            }
            catch (Exception)// ex)
            {
                //data was not retrieved successfully from the domain controller.  not a good enough reason to cancel the user create, so just move on.
            }
            finally
            {
                if (ctx != null)
                {
                    ctx.Dispose();
                }
            }

            //to avoid empty fields, but that's just a personal choice.
            if (string.IsNullOrEmpty(usr.FirstName))
            {
                usr.FirstName = windowsUserName;
            }
            if (string.IsNullOrEmpty(usr.LastName))
            {
                usr.LastName = windowsUserName;
            }
            return(usr);
        }