C#如何在WEB开发中获取当前登录域用户信息(通过LDAP)

 

C#如何在WEB开发中通过LDAP获取当前登录域用户信息,具体属性信息需结合域的配置,具体见以下代码:

前端页面适当位置显示用户名信息:

      <span class="h3">
              <span>@LoginSession.LoginUser.DisplayName</span>
      </span>
 

LoginSession.cs文件:

using System.Web;
using SPC.MVC.Models;
using SPC.MVC.Util;

namespace SPC.MVC
{
    public class LoginSession
    {
        private const string SessionKey = "Jaxxx.WUX.LoginUser";

        public static UserInfo LoginUser
        {
            get
            {
                var item = HttpContext.Current.Session[SessionKey] as UserInfo;
                if(item == null)
                {
                    UserInfo currentUser = Common.GetADUserEntity(Common.GetCurrentNTID());
                    HttpContext.Current.Session[SessionKey] = currentUser;
                    item = currentUser;
                }

                return item;
            }
        }

        public static void Logout()
        {
            //退出登录则需要清除相应的Session
            HttpContext.Current.Session.Remove(SessionKey);
        }


        public static bool IsKicked()
        {
            var item = HttpContext.Current.Session[SessionKey] as UserInfo;
            if (item == null)
            {
                return true;
            }

            return false;
        }
    }
}

 

Common.cs文件:

using System;
using System.Configuration;
using System.DirectoryServices;
using System.IO;
using System.Net.Mail;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.Hosting;
using SPC.MVC.Models;

namespace SPC.MVC.Util
{
    public static class Common
    {
        private readonly static string LDAP_PATH = ConfigurationManager.AppSettings["LDAP"];

        /// <summary>
        /// Get user id from HttpContext
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentNTID()
        {
            string identityName = HttpContext.Current.User.Identity.Name;
            int splitIndex = identityName.IndexOf('\\');
            return splitIndex > -1 ? identityName.Substring(splitIndex + 1) : identityName;
        }

        /// <summary>
        /// Get User information from AD
        /// </summary>
        /// <param name="ntid">AD用户名</param>
        /// <returns>用户实例</returns>
        public static UserInfo GetADUserEntity(string ntid)
        {
            if (string.IsNullOrEmpty(ntid))
            {
                throw new Exception("Searched user id cannot be null.");
            }

            using (HostingEnvironment.Impersonate())
            {
                DirectoryEntry entry = new DirectoryEntry(LDAP_PATH);
                DirectorySearcher searcher = new DirectorySearcher(entry);

                searcher.SearchScope = SearchScope.Subtree;
                searcher.Filter = "(&(objectClass=user)(sAMAccountName=" + ntid + "))";


                SearchResult searchResult = searcher.FindOne();
                if (searchResult != null)
                {
                    UserInfo user = new UserInfo();
                    user.UID = ntid;
                    user.Department = GetADProperty(searchResult, "department");       //具体属性信息需结合域的配置
                    user.DisplayName = GetADProperty(searchResult, "displayName");       //具体属性信息需结合域的配置
                    user.Email = GetADProperty(searchResult, "mail");       //具体属性信息需结合域的配置
                    //user.Site.SiteName = GetSiteCodeFromUserOUPath(searchResult.Path);       //具体属性信息需结合域的配置

                    return user;
                }
            }
            return null;
        }

        /// <summary>
        /// 根据属性名,在搜索结果中查找属性值
        /// </summary>
        /// <param name="searchResult">DirectorySearcher返回的搜索结果</param>
        /// <param name="propertyName">属性名</param>
        /// <returns>属性值</returns>
        private static string GetADProperty(SearchResult searchResult, string propertyName)
        {
            if (searchResult.Properties.Contains(propertyName))
            {
                return searchResult.Properties[propertyName][0].ToString();
            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 从OU中获取SITE信息
        /// </summary>
        /// <example>
        /// LDAP://corp.jaxxx.org/CN=Ming Liu,OU=Users,OU=Wuxi,OU=RegionAsia,DC=corp,DC=JAXXX,DC=ORG
        /// Site: OU=Wuxi
        /// </example>
        /// <param name="searchResult"></param>
        /// <returns></returns>
        //private static string GetSiteCodeFromUserOUPath(string ouPath)
        //{
        //    string[] ouFolders = ouPath.Split(new char[] { ',' });
        //    if (ouFolders.Length > 5)
        //    {
        //        if (ouPath.IndexOf("OU=Wuhan") > -1)
        //        {
        //            return "WUH";
        //        }
        //        string site = ouFolders[ouFolders.Length - 5].Substring(3);
        //        switch (site)
        //        {
        //            case "GPSuzhou": return "SLF";
        //            case "Huangpu": return "HUA";
        //            case "Shanghai": return "SHA";
        //            case "Singapore": return "SIN";
        //            case "Wuxi": return "WUX";
        //        }
        //    }
        //    return string.Empty;
        //}

    }

}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要通过Java使用LDAP获取AD用户和组织信息,需要使用Java的JNDI API。 以下是一个简单的Java程序,演示如何使用JNDI API连接到AD获取用户和组织信息: ``` import java.util.*; import javax.naming.*; import javax.naming.directory.*; public class ADInfo { public static void main(String[] args) { String ldapURL = "ldap://AD服务器地址:389"; String ldapUser = "CN=LDAP查询用户,OU=xxx,DC=xxx,DC=xxx"; String ldapPassword = "LDAP查询用户密码"; String searchBase = "OU=xxx,DC=xxx,DC=xxx"; Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapURL); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, ldapUser); env.put(Context.SECURITY_CREDENTIALS, ldapPassword); try { DirContext ctx = new InitialDirContext(env); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "(objectCategory=user)"; NamingEnumeration<SearchResult> results = ctx.search(searchBase, filter, searchControls); while (results.hasMore()) { SearchResult searchResult = results.next(); Attributes attributes = searchResult.getAttributes(); Attribute attribute = attributes.get("cn"); String cn = (String) attribute.get(); System.out.println(cn); } filter = "(objectCategory=organizationalUnit)"; results = ctx.search(searchBase, filter, searchControls); while (results.hasMore()) { SearchResult searchResult = results.next(); Attributes attributes = searchResult.getAttributes(); Attribute attribute = attributes.get("ou"); String ou = (String) attribute.get(); System.out.println(ou); } ctx.close(); } catch (NamingException e) { e.printStackTrace(); } } } ``` 在上面的代码,替换以下变量: - ldapURL:AD服务器地址和端口号 - ldapUser:用于查询ADLDAP用户的DN - ldapPassword:用于查询ADLDAP用户的密码 - searchBase:要搜索的AD的基本DN 该程序连接到AD并搜索用户和组织。它使用过滤器来限制搜索结果,只搜索用户和组织单位对象。它还使用SearchControls对象来设置搜索范围。 对于每个搜索结果,程序从属性提取cn或ou,并将其打印到控制台上。 请注意,此代码需要在Java应用程序包含JNDI API类路径。如果您使用Maven或Gradle之类的构建工具,则可以将以下依赖项添加到项目: ``` <dependency> <groupId>com.sun.jndi</groupId> <artifactId>ldap</artifactId> <version>1.2.1</version> </dependency> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值