標籤:style blog http ar io color os sp for
SharePoint 開啟了基於FBA的身份認證,經常會遇到使用者組使用者的問題,當我加入一個AD帳號,無法同時加入Form認證的使用者,這時,只能手動添加,比較麻煩;所以,寫了一個服務,用來每天晚上同步一下使用者組中的AD帳號和Form帳號。
原理
原理比較簡單,就是遍曆使用者組的所有使用者,同步的時候首先刪掉所有的Form帳號,然後根據所有的AD帳號去尋找Form帳號重新添加;如果碰到AD安全性群組,就去安全性群組中遍曆所有的使用者,然後尋找Form帳號添加,每天晚上定時執行。
優點
免去添加帳號的時候添加2次,而且服務可以手動執行,定時執行等;
缺點
並非即時同步,而且無法單獨在使用者組中加入Form帳號,無法滿足斷開許可權,無法滿足單獨按照人授權的情況。
總結
在自己的需求中,使用者權限控制比較簡單,均按照使用者組授權,沒有唯一使用權限設定,所以用起來還是挺好的,而且使用者對於Form帳號沒有即時的要求。如果複雜的許可權控制,還需進一步增強代碼,呵呵。
效果
執行前,只有AD帳號和AD安全性群組,如:
執行後,多出了所有Form認證的帳號,如:
程式碼片段
遍曆所有使用者組
1 using (SPSite site = new SPSite("http://SPServer")) 2 { 3 using (SPWeb web = site.RootWeb) 4 { 5 foreach (SPGroup group in web.Groups) 6 { 7 foreach (SPUser user in group.Users) 8 { 9 if (user.LoginName.IndexOf("custommembership") > 0)10 {11 group.RemoveUser(user);12 }13 }14 15 foreach (SPUser user in group.Users)16 {17 if (user.LoginName.IndexOf("domain") > 0)18 {19 group.Users.Add("i:0#.f|custommembership|" + user.Email, user.Email, user.LoginName, user.Notes);20 }21 22 if (user.IsDomainGroup)23 {24 DomainGroup(group, user.Name);25 }26 }27 }28 }29 }
去AD目錄中尋找AD帳號
1 public static string DomainGroup(SPGroup group, string DomainGroupName) 2 { 3 string returnStr = string.Empty; 4 SearchResultCollection results = null; 5 6 string filter = "(&(objectClass=group)(cn=" + DomainGroupName + "))"; 7 string connectionPrefix = "LDAP://linyu.ad.com.cn"; 8 using (DirectoryEntry root = new DirectoryEntry(connectionPrefix)) 9 {10 using (DirectorySearcher searcher = new DirectorySearcher(root))11 {12 searcher.ReferralChasing = ReferralChasingOption.All;13 searcher.SearchScope = SearchScope.Subtree;14 searcher.Filter = filter;15 results = searcher.FindAll();16 }17 }18 foreach (SearchResult sr in results)19 {20 21 DirectoryEntry deGroup = new DirectoryEntry(sr.Path);22 System.DirectoryServices.PropertyCollection pcoll = deGroup.Properties;23 int n = pcoll["member"].Count;24 Console.WriteLine(n.ToString());25 26 for (int i = 0; i < n; i++)27 {28 DirectoryEntry deUser = new DirectoryEntry(connectionPrefix + "/" + pcoll["member"][i].ToString());29 30 string username = deUser.Name.ToString();31 if (username.IndexOf("=") > 0)32 {33 username = username.Split(‘=‘)[1];34 }35 36 string email = GetProperty(deUser, "mail");37 if (email.IndexOf("@") > 0)38 {39 Console.WriteLine(username);40 group.AddUser("i:0#.f|custommembership|" + email, email, username, "");41 }42 }43 }44 return returnStr;45 }46 47 public static string GetProperty(DirectoryEntry oDE, string PropertyName)48 {49 try50 {51 if (oDE.Properties.Contains(PropertyName))52 {53 return oDE.Properties[PropertyName][0].ToString();54 }55 else56 {57 return string.Empty;58 }59 }60 catch (Exception ee)61 {62 throw ee;63 }64 }View Code
後記
思路、代碼比較簡單,希望給大家一個參考吧;運行過程中,可以封裝成TimerJob、控制台和Windows計劃任務、Windows服務等均可,看大家需要和熟悉程度吧。
好吧,就到這裡,休息,休息一下。。。
SharePoint 2013 同步FBA認證使用者