验证LDAP中的EMAIL地址是否存在
客户要做个LDAP验证,只需要输入一个mail地址,检查下只要这个地址存在于某个组里就通过,否则就不通过。代码如下
using System;
using System.Collections.Generic;
using System.Configuration;
using System.DirectoryServices;
namespace LdapLogin
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(_Default));
}
[AjaxPro.AjaxMethod]
public bool CheckLadpAccount(string path, string username, string password)
{
using (DirectoryEntry entry = new DirectoryEntry())
{
entry.Path = path;
//该用户是一个公共用户可以用来登录,也可以改成用mail来登录
entry.Username = "orcacm";
entry.Password = "1q2w3e4r";
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = "(&(objectClass=*)(mail=" + username + "))";
searcher.PropertiesToLoad.Add("mail");
searcher.PropertiesToLoad.Add("memberof");
try
{
SearchResult obj = searcher.FindOne();
if(obj!=null)
{
string[] groupsUser = GetGroupForUser(obj);
string[] groupsConfig = GetGroupForConfig();
foreach (string gu in groupsUser)
{
foreach (string gc in groupsConfig)
{
if(gu.Equals(gc))
{
return true;
}
}
}
}
return false;
}
catch (Exception ex)
{
return false;
}
}
}
//取web.config信息
[AjaxPro.AjaxMethod]
public Dictionary<string,string> LoadConfig()
{
Dictionary<string,string> dictionary=new Dictionary<string, string>();
string[] strLDAP = ConfigurationManager.AppSettings["LDAP"].Split(new char[]{';'},StringSplitOptions.RemoveEmptyEntries);
foreach (string s in strLDAP)
{
string[] strTemp = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
dictionary.Add(strTemp[0].Trim(), strTemp[1].Trim());
}
return dictionary;
}
//根据用户得到所在的组
public string[] GetGroupForUser(SearchResult obj)
{
string[] results = new string[obj.Properties["memberof"].Count];
for (int i = 0; i < obj.Properties["memberof"].Count; i++)
{
string theGroupPath = obj.Properties["memberof"][i].ToString();
results[i] = theGroupPath.Substring(3, theGroupPath.IndexOf(",") - 3);
}
return results;
}
public string[] GetGroupForConfig()
{
string[] results = ConfigurationManager.AppSettings["GROUP"].Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
return results;
}
}
}
UI代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="LdapLogin._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<link href="css/layout.css" rel="stylesheet" type="text/css" />
<title></title>
</head>
<script type="text/javascript">
var name, password, domain;
function CheckValue() {
AjaxPro.timeoutPeriod = 121000;
name = document.getElementById("txtUserMail").value;
domain = document.getElementById("dropServer").value;
if (name == "" || name.indexOf("@") == -1) {
alert("Please input correct mail");
document.getElementById("txtUserMail").focus();
return false;
}
return true;
}
function login() {
if (CheckValue()) {
LdapLogin._Default.CheckLadpAccount(domain, name, password, loginCallBack);
}
}
function GetConfig() {
LdapLogin._Default.LoadConfig(GetConfigCallBack);
}
function GetConfigCallBack(res) {
if (res.value == null) return;
var arrList = res.value;
var dropServer = document.getElementById("dropServer").options;
for (var i = 0; i < arrList.keys.length; i++) {
dropServer.add(new Option(arrList.keys[i], arrList.values[i]));
}
}
function loginCallBack(res) {
if (res.value) {
alert("login successfully!");
}
else{
alert("login failed");
}
}
</script>
<body>
<form id="form1" runat="server">
<br /><br /><br /><br /><br /><br />
<div class="lightBox">
<div class="title">
<h1>EA Domain Login</h1>
</div>
<br/>
<table>
<tr>
<td>LDAP Mail:</td>
<td><input type="text" id="txtUserMail" style="width:180px;height:20px" value="PXiang@contractor.ea.com"/></td>
</tr>
<tr>
<td></td>
<td> </td>
</tr>
<tr>
<td>LDAP Server:</td>
<td><select id="dropServer" style="width:184px;height:20px"></select></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td colspan="2" style="text-align:center"><input type="button" id="btnLogin1" value="Login" onclick="login()" style="width:140px;height:28px"></td>
</tr>
</table>
</div>
</form>
<div id="maskDiv">
<div class="loadingDiv">
<img alt="loading..." src="Images/loading.gif" /><br />
<br />
<span>Loading...</span>
</div>
</div>
</body>
</html>
<script type="text/javascript">
AjaxPro.onLoading = function(b) {
var divMask = document.getElementById("maskDiv");
if (b) {
divMask.style.display = "block";
}
else {
divMask.style.display = "none";
}
};
GetConfig();
</script>
web.config如下:
<appSettings>
<add key="LDAP" value="abc.COM,LDAP://abc.def.test.com:3268; SUZSOFT.COM,LDAP://abcsoft.com;" />
<add key="GROUP" value="#Dev Detp 5;#PhotoGroup;EA;C++ Team;Staff-SZ;Tools Development" />
</appSettings>
期间一直碰到一个错误就是:
{"Unknown error (0x80005000)"}
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_AdsObject()
at System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne)
at System.DirectoryServices.DirectorySearcher.FindOne()
at LdapLogin._Default.CheckLadpAccount(String path, String username, String password) in C:\Users\Administrator\Desktop\LdapLogin\LdapLogin\LdapLogin\Default.aspx.cs:line 29
网上找了一堆资料,这种错误的原因很多,最后发现是是大小写问题,在连接LDAP SERVER时,只要把小写改成大写就OK了。如下
LDAP://XXX.XXX.COM:3268, windows的AD好像是不接受小写的,其他的没测试过