zoukankan      html  css  js  c++  java
  • ASP.NET-AD(ActiveDirectory)用户验证

    http://blog.sina.com.cn/s/blog_5067ef490101e1ul.html

      protected void Page_Load(object sender, EventArgs e)
        {
            // 認証処理開始
            string staffCode = string.Empty;
            if (!CheckUtility.IsEmpty(Request.QueryString[ConstValue.QUERY_STRING_KEY_STFCD]))
            {
                staffCode = Request.QueryString[ConstValue.QUERY_STRING_KEY_STFCD].ToString();
            }
            string loginUserID = string.Empty;
    
            if (CheckUtility.IsEmpty(staffCode))
            {
                // URLパラメータで担当者コードが取得できなかったとき
    
                // ADよりドメイン情報の取得
                string[] name = User.Identity.Name.Split('\');
    
                // ADよりログインユーザのドメイン情報を取得
                string loginUserDomain = name[0];
                WebLogUtility.WriteDebugLog("ログインアカウント(ドメイン):" + loginUserDomain);
    
                // ADよりログインユーザIDを取得
                loginUserID = name[1];
                WebLogUtility.WriteDebugLog("ログインアカウント:" + loginUserID);
    
                LdapAuthentication ldap = new LdapAuthentication();
                staffCode = ldap.GetEmployee(loginUserDomain, loginUserID);
            }
    
            //担当者コード(AD取得)で権限マスタから権限コードを取得
            Dictionary<string, object> parameter = new Dictionary<string, object>();
            parameter.Add(StaffInfoBll.REQUEST_KEY_STAFF_CODE, staffCode);
    
            ResponseDataType response = new StaffInfoBll().Execute(parameter);
    
            // BLLからの返却値を元にSessionに値を設定
            StaffInfo staffInfo = (StaffInfo)response[StaffInfoBll.RESPONSE_KEY_STAFF_INFO];
    
            if (staffInfo == null || CheckUtility.IsEmpty(staffInfo.StfCd))
            {
                ApplException excep = new ApplException("担当者マスタにユーザーが存在しません。");
                excep.LongInUserId = staffCode;
                excep.NtAccount = loginUserID;
    
                throw excep;
            }
    
            staffInfo.NtUserCd = loginUserID;
            staffInfo.Ip = GetClientIPAddress();
    
            Session[ConstValue.SESSION_KEY_STAFF_INFO] = staffInfo;
            Session[ConstValue.SESSION_KEY_SYS_STAFF_INFO] = staffInfo;
            Session[ConstValue.SESSION_KEY_IS_AUTHENTICATED] = true;
            //}
    
            StringBuilder redirectUrl = new StringBuilder();
    
            Dictionary<string, object> redirectKey = new Dictionary<string, object>();
    
    
            // 遷移先URLの取得
            string dispId = (string)Request.QueryString[ConstValue.QUERY_STRING_KEY_DISP_ID];
    
            redirectUrl.Append(this.GetUrl(dispId));
            redirectUrl.Append("?");
            redirectUrl.Append(Request.QueryString.ToString());
    
            //セッション変数への格納
            Session.Add(ConstValue.SESSION_KEY_REDIRECT, redirectKey);
    
            // リダイレクト
            Response.Redirect(redirectUrl.ToString());
    
        }
    
        /// <summary>
        /// IPアドレスの取得
        /// </summary>
        /// <returns></returns>
        public string GetClientIPAddress()
        {
            return Request.ServerVariables["REMOTE_ADDR"];
        }
    using System;
    using System.DirectoryServices;
    using System.Configuration;
    
    using Otsuka.Application.Common.Exception;
    using Otsuka.Application.Common;
    
    /// <summary>
    /// ActiveDirectoryのユーザ情報を取得する
    /// </summary>
    public class LdapAuthentication
    {
        /// <summary>
        /// 
        /// </summary>
        private DirectoryEntry DrEntry;
    
        /// <summary>
        /// ドメイン名
        /// </summary>
        private string _domainName;
    
        /// <summary>
        /// ユーザ
        /// </summary>
        private string _userName;
    
        /// <summary>
        /// パスワード
        /// </summary>
        private string _password;
    
        /// <summary>
        /// サーバ
        /// </summary>
        private string _serverName;
    
        //第1引き数に、ユーザドメイン名を追加
        /// <summary>
        /// ユーザの所属するドメイン名
        /// </summary>
        private string _userDomainName;
    
    
        /// <summary>
        /// コンストラクタ
        /// </summary>
        public LdapAuthentication()
        {
        }
    
        /// <summary>
        /// 接続したディレクトリのユーザ情報を取得
        /// </summary>
        /// <param name="domainName">担当者のドメイン名</param>
        /// <param name="account">取得したい担当者のアカウント</param>
        /// <returns>担当者コード</returns>
        public string GetEmployee(string domainName, string account)
        {
            this._domainName = ConfigurationManager.AppSettings[ConstValue.DC_DomainName].ToString();
            this._userName = ConfigurationManager.AppSettings[ConstValue.DC_UserName].ToString();
            this._password = ConfigurationManager.AppSettings[ConstValue.DC_Password].ToString();
            this._serverName = ConfigurationManager.AppSettings[ConstValue.DC_ServerName].ToString();
            
            //Web.Configから担当者のドメインと一致するLDAP_DNを取得
            if (ConfigurationManager.AppSettings["DC_LdapDn_" + domainName.ToLower()] != null)
            {
                _userDomainName = ConfigurationManager.AppSettings["DC_LdapDn_" + domainName.ToLower()].ToString();
                _userDomainName = _userDomainName.ToLower();
    
            }
    
            //AD接続確認
            if (!AccessAD())
            {
                throw new UserNotFoundException("", "", _userName);
            }
    
            //ユーザ情報取得
            DirectorySearcher searcher = new DirectorySearcher();
            searcher.SearchRoot = DrEntry;
            searcher.Filter = "(SAMAccountName=" + account + ")";
            SearchResult result = searcher.FindOne();
    
            // アカウントが存在しない場合
            // アカウントのイニシャル項目に値が設定されていない場合
            if (result == null || result.Properties["Initials"].Count.Equals(0))
            {
                throw new UserNotFoundException("", "", account);
            }
    
            return result.Properties["Initials"][0].ToString();
        }
    
        /// <summary>
        /// ディレクトリへの接続確認
        /// </summary>
        /// <returns>true:接続可能、false:接続不可</returns>
        private bool AccessAD()
        {
            // アクセスするための情報を作成
            string domainAndUsername = _domainName + @"" + _userName;
            string[] servers = _serverName.Split(',');
            foreach (string server in servers)
            {
                string LDAP = "LDAP://" + server;
    
                //====== 2010/02/26 [CLドメイン対応] ADD START =========
                //呼出字にユーザドメイン名を追加
                if (!String.IsNullOrEmpty(_userDomainName))
                {
                    LDAP = LDAP + "/" + _userDomainName;
                }
                //====== 2010/02/26 [CLドメイン対応] ADD END =========
    
                DrEntry = new DirectoryEntry(LDAP, domainAndUsername, _password);
                try
                {
                    object navi = DrEntry.NativeObject;
                    return true;
                }
                catch
                {
                    continue;
                }
            }
            return false;
        }
    }
  • 相关阅读:
    June 26th 2017 Week 26th Monday
    June 25th 2017 Week 26th Sunday
    June 24th 2017 Week 25th Saturday
    June 23rd 2017 Week 25th Friday
    June 22nd 2017 Week 25th Thursday
    2018最佳网页设计:就是要你灵感爆棚!!!
    图片素材类Web原型制作分享-Pexels
    想要打动HR的心,UX设计师求职信究竟应该怎么写?
    【UXPA大赛企业专访】Mockplus:“设计替代开发”将成为现实
    2018年最好的医疗网站设计及配色赏析
  • 原文地址:https://www.cnblogs.com/haiy/p/4142216.html
Copyright © 2011-2022 走看看