ASP.NET-AD(ActiveDirectory)用户验证

本文介绍了一个基于Active Directory (AD) 进行用户身份验证的过程,并详细解释了如何从AD中获取用户信息,如员工代码等,以及如何利用这些信息进行权限设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

转载于:https://www.cnblogs.com/haiy/p/4142216.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值