2009年8月4日 星期二

ASP使用AD的LDAP做登入驗證

以下插入<head>

<%
MM_LoginAction = Request.ServerVariables("URL")
If Request.QueryString <> "" Then MM_LoginAction = MM_LoginAction + "?" + Server.HTMLEncode(Request.QueryString)
'#驗證的帳號表單
MM_valUsername = CStr(Request.Form("userid"))
If MM_valUsername <> "" Then
Dim MM_fldUserAuthorization
Dim MM_redirectLoginSuccess
Dim MM_redirectLoginFailed
dim strpassword,domainname
dim objDomain,objADsPath,objConnection,objCommand,objRS

MM_fldUserAuthorization = ""
'#驗證成功後前往的頁面
MM_redirectLoginSuccess = "LoginSuccess.asp"
'#驗證失敗後前往的頁面
MM_redirectLoginFailed = "LoginFailed.asp"
'#驗證的密碼表單名稱
strpassword=Request.Form("passwd")
'#驗證網域名稱,EX:domain.com,填入domain即可
domainname="domain"

on error resume next

Set objDomain = GetObject ("GC://rootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set objConnection = Server.CreateObject("ADODB.Connection")
objConnection.provider ="ADsDSOObject"
objConnection.Properties("User ID") = domainname+"\"+MM_valUsername
objConnection.Properties("Password") = strpassword
objConnection.open "Active Directory Provider"
Set objCommand = CreateObject("ADODB.Command")
Set objCommand.ActiveConnection = objConnection
objCommand.CommandText ="select cn FROM 'GC://"+objADsPath+"' where sAMAccountname='"+MM_valUsername+"'"
Set objRS = objCommand.Execute

If Err.Number = 0 Then
'#驗證成功後產生帳號的Session
Session("MM_Username") = MM_valUsername
Response.Redirect(MM_redirectLoginSuccess)
else
Response.Redirect(MM_redirectLoginFailed)
End if
End if
%>

</head>


以下插入<body>

<form id="form2" name="form1" method="POST" action="<%=MM_LoginAction%>">
<p align="center">帳號:
<label>
<input name="userid" type="text" id="userid" />
</label>
</p>
<p align="center">密碼:
<label>
<input type="password" name="passwd" id="passwd" />
</label>
</p>
<p align="center">
<label>
<input type="submit" name="login" id="login" value="送出" />
</label>
<label>
<input type="reset" name="clean" id="clean" value="重設" />
</label>
</p>
</form>


</body>

8 意見:

匿名 提到...

您好,我照貼,但都是MM_redirectLoginFailed

也沒有錯誤訊息,不知道要如何找出問題~~

Yow 提到...

先確定表單送出的帳號密碼是否正確
再檢查網域有沒有設定好(有domainname的部份)

Yow 提到...

可以試試把變數的部份(帳號、密碼、網域)直接填入測試

匿名 提到...

謝謝,我試試看~~
唉,上網找了好多資料,一直還未解決><
BY MIOKO

匿名 提到...

你好,此方法是不是PC一定要加入網域才能用,如果不加網域是不是沒法做認證呢?
BY MIOKI

Yow 提到...

不加入網域也可以進行驗証喔~

匿名 提到...

你好啊,先多謝你的分享。
不過想請問,其實有沒有方法可以做到:
(1) 只容許某群組的使用者才可登入
(2) 不同群組的使用者,於驗證後轉到不同的網頁,例如群組A的使用者轉到a.asp,群組B的使用者轉到b.asp

Yow 提到...

不好意思~
之前測試的時候並有沒找到取得群組的方式

##EasyReadMore##