项目需求:用户直接用登陆电脑的AD账号登陆系统(防止多个账号公用),权限通过获取用户所在的group来配置(group在anywhere上统一管理)。
获取当前用户group的接口:
/// <summary> /// 获取当前用户所在组列表 /// </summary> /// <param name="userName">用户AD Account</param> /// <param name="domain_server">服务器名(可传入"csf-ap-dca61.ad.shared" 或"AD")</param> /// <returns></returns> public List<string> GetGroupsForCurrentUser(string userName, string domain_server) { List<string> groupList = new List<string>(); try { // get user AD account userName = HttpContext.Current.User.Identity.Name; string[] strVals = userName.Split('\\'); if (strVals.Length < 1) return null; else userName = strVals[0]; using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain_server, null, ContextOptions.Negotiate | ContextOptions.SecureSocketLayer)) { // find the user in the identity store UserPrincipal user = UserPrincipal.FindByIdentity(ctx, userName); try { // get the groups for the user principal and // store the results in a PrincipalSearchResult object using (PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups()) { // display the names of the groups to which the // user belongs foreach (Principal group in groups) { groupList.Add(group.Name); group.Dispose(); } }//end using-2 } catch { return null; } }//end using-1 } catch (Exception ex) { throw ex; //return null; } return groupList; }
然后就遇到了问题——
HttpContext.Current.User.Identity.Name = ""
网上各种查之后发现了原因——
没有开启Windows身份验证
解决办法——
分两种情况:
1、在VS开发,选中项目 按F4,然后开启 [Windows身份验证],关闭 [匿名身份验证]
2、IIS部署,也是一样的,在身份验证里面 开启 [Windows身份验证] 和关闭 [匿名身份验证]
然后,就可以拿到登陆用户信息了!
HttpContext.Current.User.Identity.Name = "AD\\XXXXXX"
参考原文:关于 HttpContext.Current.User.Identity.Name="" 的问题