关于Sharepoint ad用户管理(源代码)

 关于Sharepoint ad用户管理(源代码)
最近一些朋友,都问我关于ad 和moss 用户 管理注册的一些问题,其实很简单,
直接把ad 加入 到moss  然后分配权限  就ok,下面是我的代码,发出来给大家参考。
有不足的地方,希望大家批评!
下面的代码是把 ad 里面的用户加入到moss 网站 ,然后分配权限

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Security.Principal;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.DirectoryServices;
using System.EnterpriseServices;
using System.Runtime.InteropServices;
using Microsoft.SharePoint;

namespace ADUserManage
{
    public partial class UserRegist : System.Web.UI.UserControl
    {

        private string ADPath = default(System.String);
        private string ADUser = default(System.String);
        private string ADPassword = default(System.String);
        /// <summary>
        /// 扮演类实例
        /// </summary>
        private static IdentityImpersonation impersonate = new IdentityImpersonation("administrator", "abc-123", "lhvm.com");

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ADPath = ConfigurationManager.AppSettings["ADPath"].ToString();
                ADUser = ConfigurationManager.AppSettings["ADAdminUser"].ToString();
                ADPassword = ConfigurationManager.AppSettings["ADAdminPassword"].ToString();
            }
            
           // SPSite site = new SPSite(@"http://lh-vmpc/personal/test");
           // SPWeb web = site.OpenWeb();
           // SPUserCollection users = web.AllUsers;
           // web.AllowUnsafeUpdates = true;
           // if (!web.HasUniqueRoleAssignments)
           // {
           //     web.BreakRoleInheritance(true);
           // }
           // SPRoleAssignment roleAssignment = new SPRoleAssignment(web.EnsureUser(@"lhvm\zhangy"));
           // roleAssignment.RoleDefinitionBindings.Add(web.RoleDefinitions["读取"]);
           // web.RoleAssignments.Add(roleAssignment);
           
           ////web.EnsureUser(@"lhvm\zhangy");
           ////// users.Add(@"lhvm\zhangy", "[email protected]", "zhangy", "haha");
           //// //SPUserCollection users = web.SiteUsers;

           ////foreach (SPUser user in users)
           ////{
           ////    Response.Write(user.Name);
           ////}

        }
        /// <summary>
        /// get Directory object
        /// </summary>
        /// <returns></returns>
        private DirectoryEntry GetDirectoryOjbect()
        {
            DirectoryEntry entry = new DirectoryEntry(ADPath, ADUser, ADPassword, AuthenticationTypes.Secure);
            return entry;
        }

        /// <summary>
        /// Get ou object
        /// </summary>
        /// <param name="ouName"></param>
        /// <returns></returns>
        private DirectoryEntry GetOuOjbect(string ouName)
        {
            DirectoryEntry de = this.GetDirectoryOjbect();
            DirectorySearcher Search = new DirectorySearcher();
            Search.SearchRoot = de;
            Search.Filter = "(OU=" + ouName + ")";
            Search.SearchScope = SearchScope.Subtree;
            SearchResult result = Search.FindOne();
            if (!(result == null))
            {
                de = new DirectoryEntry(result.Path);
                return de;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// create new user
        /// </summary>
        /// <param name="ouname"></param>
        /// <param name="commonName"></param>
        /// <param name="sAMAccountName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public DirectoryEntry CreateNewUser(string ouname,string commonName,string sAMAccountName,string password)
        {
            return CreateNewUsers(ouname, commonName, sAMAccountName, password);
        }

        /// <summary>
        /// enable user
        /// </summary>
        /// <param name="user"></param>
        public void EnableUser(DirectoryEntry user)
        {
            user.Properties["userAccountControl"].Value = 544;
            user.CommitChanges();
            user.Close();
        }

        /// <summary>
        /// change pass
        /// </summary>
        /// <param name="ude"></param>
        /// <param name="password"></param>
        public  void ChangePassword(DirectoryEntry ude, string password)
        {
           // DirectoryEntry ude = GetDirectoryeEntrys(DistinguishedName);
            ude.Invoke("SetPassword", new object[] { password });
            ude.CommitChanges();
            ude.Close();
        }

        public DirectoryEntry CreateNewUsers(string ouname,string commonName,string sAMAccountName,string password)
        {
           // DirectoryEntry entry = this.GetDirectoryOjbect();

            DirectoryEntry subentry = this.GetOuOjbect(ouname);
            impersonate.BeginImpersonate();
            DirectoryEntry deUser = subentry.Children.Add("CN=" + commonName, "user");
            deUser.Properties["sAMAccountName"].Value = sAMAccountName;

           
            deUser.CommitChanges();
            impersonate.StopImpersonate();
            this.EnableUser(deUser);
            this.ChangePassword(deUser, password);

            //deUser.Close();
            return deUser;

        }
        /// <summary>
        /// get  ad user  add moss
        /// </summary>
        /// <param name="DomianUser"></param>
        /// <param name="commonName"></param>
        /// <returns></returns>
        private bool GetAdToMossUser(string DomianUser,string commonName)
        {
            try
            {

                SPSite site = new SPSite(@"http://lh-vmpc/personal/test");
                SPWeb web = site.OpenWeb();
                SPUserCollection users = web.AllUsers;
                web.AllowUnsafeUpdates = true;

                users.Add(DomianUser, "[email protected]", commonName, commonName);

                if (!web.HasUniqueRoleAssignments)
                {
                    web.BreakRoleInheritance(true);
                }
                SPRoleAssignment roleAssignment = new SPRoleAssignment(web.EnsureUser(DomianUser));
                roleAssignment.RoleDefinitionBindings.Add(web.RoleDefinitions["读取"]);
                web.RoleAssignments.Add(roleAssignment);
                return true;
            }
            catch
            {
                return false;
            }

        }

        protected void btnCreateUser_Click(object sender, EventArgs e)
        {
            if (this.tbUserName.Text == "")
            {
                Response.Write("<script>alert('用户名不能为空');</script>");
            }
            else if (this.tbPassword.Text.Trim() != this.tbPwd.Text.Trim())
            {
                Response.Write("<script>alert('密码不相同')</script>");
            }
            else
            {
                DirectoryEntry en = this.CreateNewUser("SharePoint部门", this.tbUserName.Text.Trim(), this.tbUserName.Text.Trim(), this.tbPassword.Text.Trim());
                if (en != null)
                {

                    if (this.GetAdToMossUser("lhvm" + "\\"+this.tbUserName.Text.Trim(), this.tbUserName.Text.Trim()))
                    {
                        Response.Write("<script>alert('恭喜注册成功!')</script>");
                    }
                    else
                    {
                        Response.Write("<script>alert('恭喜注册!')</script>");
                    }

                  

                }
                else
                {

                    Response.Write("<script>alert('注册失败!')</script>");
       
                }
            }
              

        }
    }

    /// <summary>
    /// 用户模拟角色类。实现在程序段内进行用户角色模拟。
    /// </summary>
    public class IdentityImpersonation
    {
        /// <summary>
        /// Logons the user.
        /// </summary>
        /// <param name="lpszUsername">The LPSZ username.</param>
        /// <param name="lpszDomain">The LPSZ domain.</param>
        /// <param name="lpszPassword">The LPSZ password.</param>
        /// <param name="dwLogonType">Type of the dw logon.</param>
        /// <param name="dwLogonProvider">The dw logon provider.</param>
        /// <param name="phToken">The ph token.</param>
        /// <returns></returns>
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

        /// <summary>
        /// Duplicates the token.
        /// </summary>
        /// <param name="ExistingTokenHandle">The existing token handle.</param>
        /// <param name="SECURITY_IMPERSONATION_LEVEL">The SECURIT y_ IMPERSONATIO n_ LEVEL.</param>
        /// <param name="DuplicateTokenHandle">The duplicate token handle.</param>
        /// <returns></returns>
        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);

        /// <summary>
        /// Closes the handle.
        /// </summary>
        /// <param name="handle">The handle.</param>
        /// <returns></returns>
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public extern static bool CloseHandle(IntPtr handle);

        // 要模拟的用户的用户名、密码、域(机器名)
        private String _sImperUsername;
        private String _sImperPassword;
        private String _sImperDomain;

        //记录模拟上下文
        private WindowsImpersonationContext _imperContext;
        private IntPtr _adminToken;
        private IntPtr _dupeToken;

        // 是否已停止模拟
        private Boolean _bClosed;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="impersonationUsername">所要模拟的用户的用户名</param>
        /// <param name="impersonationPassword">所要模拟的用户的密码</param>
        /// <param name="impersonationDomain">所要模拟的用户所在的域</param>
        public IdentityImpersonation(String impersonationUsername, String impersonationPassword, String impersonationDomain)
        {
            _sImperUsername = impersonationUsername;
            _sImperPassword = impersonationPassword;
            _sImperDomain = impersonationDomain;
            _adminToken = IntPtr.Zero;
            _dupeToken = IntPtr.Zero;
            _bClosed = true;
        }

        /// <summary>
        /// 析构函数
        /// </summary>
        ~IdentityImpersonation()
        {
            if (!_bClosed)
            {
                StopImpersonate();
            }
        }

        /// <summary>
        /// 开始身份角色模拟。
        /// </summary>
        /// <returns></returns>
        public Boolean BeginImpersonate()
        {
            Boolean bLogined = LogonUser(_sImperUsername, _sImperDomain, _sImperPassword, 2, 0, ref _adminToken);
            if (!bLogined)
            {
                return false;
            }

            Boolean bDuped = DuplicateToken(_adminToken, 2, ref _dupeToken);
            if (!bDuped)
            {
                return false;
            }

            WindowsIdentity fakeId = new WindowsIdentity(_dupeToken);
            _imperContext = fakeId.Impersonate();
            _bClosed = false;

            return true;
        }

        /// <summary>
        /// 停止身分角色模拟。
        /// </summary>
        public void StopImpersonate()
        {
            //_imperContext.Undo();

            CloseHandle(_dupeToken);
            CloseHandle(_adminToken);
            _bClosed = true;
        }
    }
}



代码很简单,只是希望大家明白一些道理


你可能感兴趣的:(SharePoint)