pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

在 C# 中驗證遠程 Active Directory 的用戶

Validate users of Remote Active Directory in C#(在 C# 中驗證遠程 Active Directory 的用戶)
本文介紹了在 C# 中驗證遠程 Active Directory 的用戶的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我嘗試從我的機??器驗證屬于遠程 ActiveDirectory 的用戶,這與當前機器或用戶域不同.我的機器和遠程 ActiveDirectory 機器之間將不存在信任.

初步嘗試

我嘗試對用戶進行身份驗證(輸入:sAMAccountName、機器的 ipaddress、機器的域用戶名(管理員")和機器的密碼(***).能夠得到具有 'sAMAccountName' 的用戶確實存在于 ActiveDirectory 中的結果.

我的要求:

  1. 假設已經在 ActiveDirectory 中創建了一個用戶(qwerty")

  2. 從我的本地機器,我將獲得以下信息,

    一個.遠程 ActiveDirectory ipaddress

    B.遠程 ActiveDirectory 計算機的用戶名和密碼.

    c.用戶qwerty"的用戶名和密碼

  3. 我需要檢查遠程 ActiveDirectory 的用戶列表中是否存在用戶qwerty",并驗證輸入的 密碼 在 ActiveDirectory 的用戶列表中是否相同

我嘗試過的代碼:

 DirectoryEntry entry = new DirectoryEntry("LDAP://ipaddress/DC=dinesh,DC=com", name, password);DirectorySearcher searcher = new DirectorySearcher(entry);searcher.Filter = "(sAMAccountName=" + 姓名 + ")";嘗試{SearchResult adsSearchResult = adsSearcher.FindOne();isValid = true;adsEntry.Close();}捕獲(異常前){adsEntry.Close();}

在驗證遠程 ActiveDirectory 中的用戶之前,我是否需要在本地計算機和遠程 ActiveDirectory 計算機之間建立信任?如果是,請告訴如何做到;

創建信任后,如何驗證用戶?

============================================================================

我可以使用 Rainer 建議的解決方案,但遇到了一個新問題.當我通過不同機器上的 C# 代碼創建新用戶時,某些屬性設置不正確.

是否需要在創建用戶時強制設置?

解決方案

首先是一些基礎知識(獨立于這個問題)

身份驗證

系統會檢查 Bob 是否真的是 Bob.在 Active Directory 環境中,這通常是通過從工作站登錄域來完成的,Bob 輸入他的用戶名和密碼,然后他獲得 Kerberos 票證.稍后,如果他想訪問例如遠程文件服務器上的文件共享,他不再需要登錄,無需輸入用戶名/密碼即可訪問文件.

授權

系統檢查允許 Bob 訪問哪些資源.通常Bob在域組中,一個組在資源的ACL(訪問控制列表)中.

如果有多個信任域,Bob 需要在一個域中登錄,并且可以訪問所有其他域中的資源.這是使用 Active Directory 的主要原因之一:單點登錄

檢查用戶/密碼是否有效

如果您有用戶名和密碼并想檢查密碼是否有效,則必須登錄域.沒有辦法僅僅檢查密碼是否正確".登錄是指:如果有安全策略如果超過 3 次無效登錄,則鎖定帳戶",即使您只想檢查用戶+密碼",檢查錯誤密碼也會鎖定帳戶.

使用 .NET 目錄服務功能

我在這里假設該進程要么由人類帳戶作為普通程序運行,要么該程序是 Windows 服務或在域技術用戶"帳戶下運行的計劃任務.在這種情況下,您無需提供使用 AD 功能的憑據.如果訪問其他信任的 AD 域,也是如此.如果您想登錄到外域",并且沒有信任,則需要提供用戶名+密碼(如您的代碼中所示).

手動"驗證用戶

通常不需要這樣做.示例:ASP.NET Intranet 使用情況.用戶訪問當前域或信任域上的 Web 應用程序,身份驗證由瀏覽器和 IIS在后臺"完成(如果集成的 Windows 身份驗證打開).所以你永遠不需要在應用程序中處理用戶密碼.

我沒有看到很多使用代碼處理密碼的用例.

有人可能認為您的程序是用于存儲緊急用戶帳戶/密碼的輔助工具.并且您想定期檢查這些帳戶是否有效.

這是一個簡單的檢查方法:

使用 System.DirectoryServices.AccountManagement;...主體上下文主體上下文 =新的 PrincipalContext(ContextType.Domain, "192.168.1.1");bool userValid = principalContext.ValidateCredentials(name, password);

還可以使用較舊的原始 ADSI 函數:

使用 System.DirectoryServices;....bool userOk = false;string realName = string.Empty;使用 (DirectoryEntry directoryEntry =new DirectoryEntry"LDAP://192.168.1.1/DC=ad,DC=local", name, password)){使用 (DirectorySearcher searcher = new DirectorySearcher(directoryEntry)){searcher.Filter = "(samaccountname=" + name + ")";searcher.PropertiesToLoad.Add("displayname");SearchResult adsSearchResult = searcher.FindOne();如果(adsSearchResult != null){if (adsSearchResult.Properties["displayname"].Count == 1){realName = (string)adsSearchResult.Properties["displayname"][0];}用戶確定 = 真;}}}

如果您的真正要求實際上是用戶+密碼的有效性檢查,您可以通過以下方式之一進行.

但是,如果是普通應用程序",只想檢查輸入的憑據是否有效,則應該重新考慮您的邏輯.在這種情況下,您最好依靠 AD 的單點登錄功能.

如果還有什么問題,歡迎留言.

<塊引用><塊引用>

B.遠程 ActiveDirectory 計算機的用戶名和密碼.

這聽起來有點不清楚.我假設您的意思是遠程域中的用戶名和相應的密碼".

還有機器賬號的概念,就是主機名后加$.但那是另一個話題了.

<小時>

創建新用戶

選項 1

using (DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://192.168.1.1/CN=Users,DC=ad,DC=local",姓名、密碼)){使用 (DirectoryEntry newUser = directoryEntry.Children.Add("CN=CharlesBarker", "user")){newUser.Properties["sAMAccountName"].Value = "CharlesBarker";newUser.Properties["givenName"].Value = "Charles";newUser.Properties["sn"].Value = "Barker";newUser.Properties["displayName"].Value = "CharlesBarker";newUser.Properties["userPrincipalName"].Value = "CharlesBarker";newUser.CommitChanges();}}

選項 2

using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, "192.168.1.1","CN=Users,DC=ad,DC=local", 姓名, 密碼)){使用 (UserPrincipal userPrincipal = new UserPrincipal(principalContext)){userPrincipal.Name = "CharlesBarker";userPrincipal.SamAccountName = "CharlesBarker";userPrincipal.GivenName = "查爾斯";userPrincipal.Surname = "巴克";userPrincipal.DisplayName = "CharlesBarker";userPrincipal.UserPrincipalName = "CharlesBarker";userPrincipal.Save();}}

我留給你一個練習,找出哪個屬性進入哪個用戶對話框輸入字段:-)

I try to authenticate users belonging to remote ActiveDirectory from my machine, which is not the same domain as the current machine or user domain. There will be no trust between my machine and remote ActiveDirectory machine.

Initial Try

I tried to authenticate a user(Input: sAMAccountName, machine's ipaddress, machine's domain username("Administrator") and machine's password(***). Able to get result that the user with 'sAMAccountName' do exist in ActiveDirectory.

My Requirement:

  1. Imagine that already a user("qwerty") is created in ActiveDirectory

  2. From my local machine, I will have the following information,

    a. Remote ActiveDirectory ipaddress

    b. Remote ActiveDirectory machine's username and password.

    c. Username and password of User "qwerty"

  3. I need to check whether User "qwerty" is present in remote ActiveDirectory's users list and validate whether the password entered is same in ActiveDirectory's Users list

Code I tried:

        DirectoryEntry entry = new DirectoryEntry("LDAP://ipaddress/DC=dinesh,DC=com", name, password);
        DirectorySearcher searcher = new DirectorySearcher(entry);
        searcher.Filter = "(sAMAccountName=" + name + ")";

        try
        {
            SearchResult adsSearchResult = adsSearcher.FindOne();
            isValid = true;
            adsEntry.Close();
        }
        catch (Exception ex)
        {
            adsEntry.Close();
        }

Do I need to create a trust between local machine and remote ActiveDirectory machine before validating Users in a remote ActiveDirectory? If yes please tell how it can be done;

After creating trust, how can I validate Users?

===========================================================================

I am able to use the solution suggested by Rainer, but with a new problem. When I create a new user via C# code from a different machine, then some properties do not set properly.

Does this need to be set compulsorily while creating user?

解決方案

First some basics (independent of this question)

Authentication

The system checks if Bob is really Bob. In an Active Directory environment, this is usually done with a domain login from the workstation, Bob enters his username and password, and he gets a Kerberos ticket. Later, if he wants to access e.g. a file share on a remote fileserver, he does not need to login anymore, and can access the files without entering username/password.

Authorization

The system checks which resources Bob is allowed to access. Usually Bob is in domain groups, and a group is in the ACL (access control list) of the resource.

If there are multiple trusting domains, Bob needs to login in one domain, and can access resources in all other domains. This is one of the main reasons using Active Directory: single sign on

Checking if user / password is valid

If you have a username and password and want to check if the password is valid, you have to do a login to the domain. There is no way of just "checking if the password is correct". Login means: if there is a security policy "lock account if more than 3 invalid logins", the account will be locked out checking with wrong password, even if you "only want to check the user+password".

Using .NET Directory Service functions

I assume here that the process is either run by a human account as a normal program, or the program is a Windows service or a scheduled task which runs under a domain "technical user" account. In this case, you do not need to provide credentials for using the AD functions. If accessing other trusting AD domains, this is also true. If you want to login to a "foreign domain", and there is no trust, you need to provide a username+password (as in your code).

"Manually" authenticating a user

Normally, this should not be needed. Example: ASP.NET intranet usage. The user access a web application on the current domain or trusting domain, the authentication is done "in the background" by browser and IIS (if integrated Windows authentication is on). So you never need to handle user passwords in the application.

I don’t see many use cases where a password is handled by code.

One may that your program is a helper tool for storing emergency user accounts/passwords. And you want to check periodically if these accounts are valid.

This is a simple way to check:

using System.DirectoryServices.AccountManagement;
...

PrincipalContext principalContext = 
     new PrincipalContext(ContextType.Domain, "192.168.1.1");

bool userValid = principalContext.ValidateCredentials(name, password);

One can also use the older, raw ADSI functions:

using System.DirectoryServices;
....

bool userOk = false;
string realName = string.Empty;

using (DirectoryEntry directoryEntry = 
   new DirectoryEntry"LDAP://192.168.1.1/DC=ad,DC=local", name, password))
{
    using (DirectorySearcher searcher = new DirectorySearcher(directoryEntry))
    {
        searcher.Filter = "(samaccountname=" + name + ")";
        searcher.PropertiesToLoad.Add("displayname");

        SearchResult adsSearchResult = searcher.FindOne();

        if (adsSearchResult != null)
        {
            if (adsSearchResult.Properties["displayname"].Count == 1)
            {   
                realName = (string)adsSearchResult.Properties["displayname"][0];
            }
            userOk = true;
        }
    }
}   

If your real requirement is actually a validity check of user+password, you can do it in one of these ways.

However, if it is a "normal application", which just wants to check if the entered credentials are valid, you should rethink your logic. In this case, you better should rely on the single sign on capabilities of AD.

If there are further questions, please comment.

b. Remote ActiveDirectory machine's username and password.

This sounds a bit unclear. I assume you mean "a username and corresponding password in the remote domain".

There is also the concept of a machine account, which is the hostname appended with $. But that's another topic.


Creating new user

Option 1

using (DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://192.168.1.1/CN=Users,DC=ad,DC=local", 
        name, password))
{
    using (DirectoryEntry newUser = directoryEntry.Children.Add("CN=CharlesBarker", "user"))
    {
        newUser.Properties["sAMAccountName"].Value = "CharlesBarker";
        newUser.Properties["givenName"].Value = "Charles";
        newUser.Properties["sn"].Value = "Barker";
        newUser.Properties["displayName"].Value = "CharlesBarker";
        newUser.Properties["userPrincipalName"].Value = "CharlesBarker";
        newUser.CommitChanges();
    }
}

Option 2

using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, "192.168.1.1", 
    "CN=Users,DC=ad,DC=local", name, password))
{
    using (UserPrincipal userPrincipal = new UserPrincipal(principalContext))
    {
        userPrincipal.Name = "CharlesBarker";
        userPrincipal.SamAccountName = "CharlesBarker";
        userPrincipal.GivenName = "Charles";
        userPrincipal.Surname = "Barker";
        userPrincipal.DisplayName = "CharlesBarker";
        userPrincipal.UserPrincipalName = "CharlesBarker";
        userPrincipal.Save();
    }
}

I leave as an exercise to you to find out which attribute goes into which User dialog entry field :-)

這篇關于在 C# 中驗證遠程 Active Directory 的用戶的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

Why shouldn#39;t I always use nullable types in C#(為什么我不應該總是在 C# 中使用可空類型)
C# HasValue vs !=null(C# HasValue vs !=null)
C# ADO.NET: nulls and DbNull -- is there more efficient syntax?(C# ADO.NET:空值和 DbNull —— 有沒有更高效的語法?)
How to set null value to int in c#?(如何在c#中將空值設置為int?)
How to handle nulls in LINQ when using Min or Max?(使用 Min 或 Max 時如何處理 LINQ 中的空值?)
Method call if not null in C#(在 C# 中如果不為 null 的方法調用)
主站蜘蛛池模板: led冷热冲击试验箱_LED高低温冲击试验箱_老化试验箱-爱佩百科 | STRO|DTRO-STRO反渗透膜(科普)_碟滤 | 炉门刀边腹板,焦化设备配件,焦化焦炉设备_沧州瑞创机械制造有限公司 | 加中寰球移民官网-美国移民公司,移民机构,移民中介,移民咨询,投资移民 | 室内室外厚型|超薄型|非膨胀型钢结构防火涂料_隧道专用防火涂料厂家|电话|价格|批发|施工 | 酶联免疫分析仪-多管旋涡混合仪|混合器-莱普特科学仪器(北京)有限公司 | 低粘度纤维素|混凝土灌浆料|有机硅憎水粉|聚羧酸减水剂-南京斯泰宝 | 沉降天平_沉降粒度仪_液体比重仪-上海方瑞仪器有限公司 | 动物麻醉机-数显脑立体定位仪-北京易则佳科技有限公司 | 南京和瑞包装有限公司 | 道康宁消泡剂-瓦克-大川进口消泡剂供应商 | 工业废水处理|污水处理厂|废水治理设备工程技术公司-苏州瑞美迪 今日娱乐圈——影视剧集_八卦娱乐_明星八卦_最新娱乐八卦新闻 | 附着力促进剂-尼龙处理剂-PP处理剂-金属附着力处理剂-东莞市炅盛塑胶科技有限公司 | 硅PU球场、篮球场地面施工「水性、环保、弹性」硅PU材料生产厂家-广东中星体育公司 | 大流量卧式砂磨机_强力分散机_双行星双动力混合机_同心双轴搅拌机-莱州市龙跃化工机械有限公司 | 苏州伊诺尔拆除公司_专业酒店厂房拆除_商场学校拆除_办公楼房屋拆除_家工装拆除拆旧 | Copeland/谷轮压缩机,谷轮半封闭压缩机,谷轮涡旋压缩机,型号规格,技术参数,尺寸图片,价格经销商 CTP磁天平|小电容测量仪|阴阳极极化_双液系沸点测定仪|dsj电渗实验装置-南京桑力电子设备厂 | 【甲方装饰】合肥工装公司-合肥装修设计公司,专业从事安徽办公室、店面、售楼部、餐饮店、厂房装修设计服务 | 不锈钢螺丝 - 六角螺丝厂家 - 不锈钢紧固件 - 万千紧固件--紧固件一站式采购 | 高铝轻质保温砖_刚玉莫来石砖厂家_轻质耐火砖价格 | 3dmax渲染-效果图渲染-影视动画渲染-北京快渲科技有限公司 | 识禅_对禅的了解,从这里开始| 南汇8424西瓜_南汇玉菇甜瓜-南汇水蜜桃价格 | 澳门精准正版免费大全,2025新澳门全年免费,新澳天天开奖免费资料大全最新,新澳2025今晚开奖资料,新澳马今天最快最新图库-首页-东莞市傲马网络科技有限公司 | 科普仪器菏泽市教育教学仪器总厂 | RV减速机-蜗轮蜗杆减速机-洗车机减速机-减速机厂家-艾思捷 | 润滑脂-高温润滑脂-轴承润滑脂-食品级润滑油-索科润滑油脂厂家 | NMRV减速机|铝合金减速机|蜗轮蜗杆减速机|NMRV减速机厂家-东莞市台机减速机有限公司 | 编织人生 - 权威手工编织网站,编织爱好者学习毛衣编织的门户网站,织毛衣就上编织人生网-编织人生 | 双工位钻铣攻牙机-转换工作台钻攻中心-钻铣攻牙机一体机-浙江利硕自动化设备有限公司 | 撕碎机,撕破机,双轴破碎机-大件垃圾破碎机厂家 | 吸音板,隔音板,吸音材料,吸音板价格,声学材料 - 佛山诺声吸音板厂家 | 排烟防火阀-消防排烟风机-正压送风口-厂家-价格-哪家好-德州鑫港旺通风设备有限公司 | 电子厂招聘_工厂招聘_普工招聘_小时工招聘信息平台-众立方招工网 | 交通气象站_能见度检测仪_路面状况监测站- 天合环境科技 | 喷码机,激光喷码打码机,鸡蛋打码机,手持打码机,自动喷码机,一物一码防伪溯源-恒欣瑞达有限公司 | 河南不锈钢水箱_地埋水箱_镀锌板水箱_消防水箱厂家-河南联固供水设备有限公司 | 校园气象站_超声波气象站_农业气象站_雨量监测站_风途科技 | 高压油管,液压接头,液压附件-烟台市正诚液压附件| 砖机托板价格|免烧砖托板|空心砖托板厂家_山东宏升砖机托板厂 | 超声波分散机-均质机-萃取仪-超声波涂料分散设备-杭州精浩 |