且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过表单在ASP.NET Web API中实现Active Directory身份验证?

更新时间:2022-12-06 16:57:22

//为项目添加3个引用

System.DirectoryService

System.DirectoryService.Protocols

System.DirectoryService.AccountManagement



//创建一个bool方法



public bool IsAuthenticatedUser(string srvr,string usr,string password)

{

bool authenticated = false;

try

{

DirectoryEntry entry = new DirectoryEntry(srvr,usr,password);

object nativeObject = entry.NativeObject;

Object obj = entry.NativeObject;

authenticated = true;

}

catch

{

// LableError.Text =无效的用户名;

}

返回认证;

}







//然后将此代码放入登录按钮



protected void login_Click(object sender,EventArgs e)

{

if(IsAuthenticatedUser(,YourADName \\ + UserNameText.Text,PasswordText.Text))

{

//做点重定向的事情

}

其他

{



errorMessage.Text =无效用户;

}





}
// Add 3 references to your project
System.DirectoryService
System.DirectoryService.Protocols
System.DirectoryService.AccountManagement

// create a bool method

public bool IsAuthenticatedUser(string srvr, string usr, string password)
{
bool authenticated = false;
try
{
DirectoryEntry entry = new DirectoryEntry(srvr, usr, password);
object nativeObject = entry.NativeObject;
Object obj = entry.NativeObject;
authenticated = true;
}
catch
{
// LableError.Text = "Invalid UserName";
}
return authenticated;
}



// Then put this code inside the login button

protected void login_Click(object sender, EventArgs e)
{
if (IsAuthenticatedUser("", "YourADName\\" + UserNameText.Text,PasswordText.Text))
{
// Do something such as redirect somewhere
}
else
{

errorMessage.Text = "Invalid User";
}


}