ASP.NET-AD(ActiveDirectory)使用者驗證

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   os   sp   for   

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;    }}

 

ASP.NET-AD(ActiveDirectory)使用者驗證

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.