ASP.NET 中通过Form身份验证 来模拟Windows 域服务身份验证的方法
This step-by-step article demonstrates how an ASP.NET application can use Forms authentication to permit users to authenticate against the Active Directory by using the Lightweight Directory Access Protocol (LDAP). After the user is authenticated and redirected, you can use the Application_AuthenticateRequest method of the Global.asax file to store a GenericPrincipal object in the HttpContext.User property that flows throughout the request.
Create an ASP.NET Web application in Visual C# .NET
Follow these steps to create a new ASP.NET Web application named FormsAuthAd in Visual C# .NET:
- Start Microsoft Visual Studio .NET.
- On the File menu, point to New, and then click Project.
- Click Visual C# Projects under Project Types, and then click ASP.NET Web Application under Templates.
- In the Location box, replace WebApplication1 with FormsAuthAd.
- Click OK.
- Right-click the References node in Solution Explorer, and then click Add Reference.
- On the .NET tab in the Add Reference dialog box, click System.DirectoryServices.dll, click Select, and then click OK.
Write the authentication code
Follow these steps to create a new class file named LdapAuthentication.cs:
- In Solution Explorer, right-click the project node, point to Add, and then click Add New Item.
- Click Class under Templates.
- Type LdapAuthentication.cs in the Name box, and then click Open.
- Replace the existing code in the LdapAuthentication.cs file with the following code.
using System;
using System.Text;
using System.Collections;
using System.DirectoryServices; namespace FormsAuth
{
public class LdapAuthentication
{
private String _path;
private String _filterAttribute; public LdapAuthentication(String path)
{
_path = path;
} public bool IsAuthenticated(String domain, String username, String pwd)
{
String domainAndUsername = domain + @"\" + username;
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd); try
{ //Bind to the native AdsObject to force authentication.
Object obj = entry.NativeObject; DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne(); if(null == result)
{
return false;
} //Update the new path to the user in the directory.
_path = result.Path;
_filterAttribute = (String)result.Properties["cn"][];
}
catch (Exception ex)
{
throw new Exception("Error authenticating user. " + ex.Message);
} return true;
} public String GetGroups()
{
DirectorySearcher search = new DirectorySearcher(_path);
search.Filter = "(cn=" + _filterAttribute + ")";
search.PropertiesToLoad.Add("memberOf");
StringBuilder groupNames = new StringBuilder(); try
{
SearchResult result = search.FindOne(); int propertyCount = result.Properties["memberOf"].Count; String dn;
int equalsIndex, commaIndex; for(int propertyCounter = ; propertyCounter < propertyCount; propertyCounter++)
{
dn = (String)result.Properties["memberOf"][propertyCounter]; equalsIndex = dn.IndexOf("=", );
commaIndex = dn.IndexOf(",", );
if(- == equalsIndex)
{
return null;
} groupNames.Append(dn.Substring((equalsIndex + ), (commaIndex - equalsIndex) - ));
groupNames.Append("|"); }
}
catch(Exception ex)
{
throw new Exception("Error obtaining group names. " + ex.Message);
}
return groupNames.ToString();
}
}
}
The authentication code accepts a domain, a user name, a password, and a path to the tree in the Active Directory. This code uses the LDAP directory provider.
The code in the Logon.aspx page calls the LdapAuthentication.IsAuthenticated method and passes in the credentials that are collected from the user. Then, a DirectoryEntry object is created with the path to the directory tree, the user name, and the password. The user name must be in the "domain\username" format. The DirectoryEntry object then tries to force the AdsObject binding by obtaining the NativeObject property. If this succeeds, the CN attribute for the user is obtained by creating a DirectorySearcher object and by filtering on the SAMAccountName. After the user is authenticated, the IsAuthenticated method returns true.
To obtain a list of groups that the user belongs to, this code calls the LdapAuthentication.GetGroups method. The LdapAuthentication.GetGroups method obtains a list of security and distribution groups that the user belongs to by creating a DirectorySearcher object and by filtering according to the memberOf attribute. This method returns a list of groups that is separated by pipes (|).
Notice that the LdapAuthentication.GetGroups method manipulates and truncates strings. This reduces the length of the string that is stored in the authentication cookie. If the string is not truncated, the format of each group appears as follows.
CN=...,...,DC=domain,DC=com
This can create a very long string. If the length of this string is greater than the length of the cookie, browsers may not accept the authentication cookie, and you will be redirected to the logon page. However, if you are in a multi-domain environment, you may have to keep the domain name with the group name because groups in different domains can have the same group name. You have to keep the domain name to differentiate one group from another.
Most browsers support cookies of up to 4096 bytes. If this string may potentially exceed the length of the cookie, you may want to store the group information in the ASP.NET Cache object or in a database. Alternatively, you may want to encrypt the group information and store this information in a hidden form field.
Write the Global.asax code
The code in the Global.asax file provides an Application_AuthenticateRequest event handler. This event handler retrieves the authentication cookie from the Context.Request.Cookies collection, decrypts the cookie, and retrieves the list of groups that will be stored in the FormsAuthenticationTicket.UserData property. The groups appear in a pipe-separated list that is created in the Logon.aspx page.
The code parses the string in a string array to create a GenericPrincipal object. After the GenericPrincipal object is created, this object is placed in the HttpContext.User property.
- In Solution Explorer, right-click Global.asax, and then click .
- Add the following code at the top of the code-behind Global.asax.cs file:
using System.Web.Security;
using System.Security.Principal;
- Replace the existing empty event handler for the Application_AuthenticateRequest with the following code.
void Application_AuthenticateRequest(Object sender, EventArgs e)
{
String cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName]; if(null == authCookie)
{//There is no authentication cookie.
return;
} FormsAuthenticationTicket authTicket = null; try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch(Exception ex)
{
//Write the exception to the Event Log.
return;
} if(null == authTicket)
{//Cookie failed to decrypt.
return;
} //When the ticket was created, the UserData property was assigned a
//pipe-delimited string of group names.
String[] groups = authTicket.UserData.Split(new char[]{'|'}); //Create an Identity.
GenericIdentity id = new GenericIdentity(authTicket.Name, "LdapAuthentication"); //This principal flows throughout the request.
GenericPrincipal principal = new GenericPrincipal(id, groups); Context.User = principal; }
Modify the Web.config file
In this section, you configure the <forms>, the <authentication>, and the <authorization> elements in the Web.config file. With these changes, only authenticated users can access the application, and unauthenticated requests are redirected to a Logon.aspx page. You can modify this configuration to permit only certain users and groups access to the application.
Replace the existing code in the Web.config file with the following code.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<authentication mode="Forms">
<forms loginUrl="logon.aspx" name="adAuthCookie" timeout="10" path="/" >
</forms>
</authentication>
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
<identity impersonate="true" />
</system.web>
</configuration>
Notice the <identity impersonate="true" /> configuration element. This causes ASP.NET to impersonate the account that is configured as the anonymous account from Microsoft Internet Information Services (IIS). As a result of this configuration, all requests to this application run under the security context of the configured account. The user provides credentials to authenticate against the Active Directory, but the account that accesses the Active Directory is the configured account. For more information, see the References section.
Configure IIS for anonymous authentication
To configure IIS for anonymous authentication, follow these steps:
- 在要做配置的站点中双击身份认证
- 启用匿名身份验证
- 确保应用程序的匿名帐户对 Active Directory 域服务具有访问权限。
Create the Logon.aspx page
Follow these steps to create a new ASP.NET Web Form named Logon.aspx:
In Solution Explorer, right-click the project node, point to Add, and then click Add Web Form.
- Type Logon.aspx in the Name box, and then click Open.
- In Solution Explorer, right-click Logon.aspx, and then click View Designer.
- Click the HTML tab in the Designer.
- Replace the existing code with the following code.
<%@ Page language="c#" AutoEventWireup="true" %>
<%@ Import Namespace="FormsAuth" %>
<html>
<body>
<form id="Login" method="post" runat="server">
<asp:Label ID="Label1" Runat=server >Domain:</asp:Label>
<asp:TextBox ID="txtDomain" Runat=server ></asp:TextBox><br>
<asp:Label ID="Label2" Runat=server >Username:</asp:Label>
<asp:TextBox ID=txtUsername Runat=server ></asp:TextBox><br>
<asp:Label ID="Label3" Runat=server >Password:</asp:Label>
<asp:TextBox ID="txtPassword" Runat=server TextMode=Password></asp:TextBox><br>
<asp:Button ID="btnLogin" Runat=server Text="Login" OnClick="Login_Click"></asp:Button><br>
<asp:Label ID="errorLabel" Runat=server ForeColor=#ff3300></asp:Label><br>
<asp:CheckBox ID=chkPersist Runat=server Text="Persist Cookie" />
</form>
</body>
</html>
<script runat=server>
void Login_Click(Object sender, EventArgs e)
{
String adPath = "LDAP://corp.com"; //Fully-qualified Domain Name
LdapAuthentication adAuth = new LdapAuthentication(adPath);
try
{
if(true == adAuth.IsAuthenticated(txtDomain.Text, txtUsername.Text, txtPassword.Text))
{
String groups = adAuth.GetGroups(); //Create the ticket, and add the groups.
bool isCookiePersistent = chkPersist.Checked;
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, txtUsername.Text,
DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, groups); //Encrypt the ticket.
String encryptedTicket = FormsAuthentication.Encrypt(authTicket); //Create a cookie, and then add the encrypted ticket to the cookie as data.
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); if(true == isCookiePersistent)
authCookie.Expires = authTicket.Expiration; //Add the cookie to the outgoing cookies collection.
Response.Cookies.Add(authCookie); //You can redirect now.
Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, false));
}
else
{
errorLabel.Text = "Authentication did not succeed. Check user name and password.";
}
}
catch(Exception ex)
{
errorLabel.Text = "Error authenticating. " + ex.Message;
}
}
</script>
- Modify the path in the Logon.aspx page to point to your LDAP Directory server.
The Logon.aspx page is a page that collects the information from the user and call methods on the LdapAuthentication class. After the code authenticates the user and obtains a list of groups, the code creates a FormsAuthenticationTicket object, encrypts the ticket, adds the encrypted ticket to a cookie, adds the cookie to the HttpResponse.Cookies collection, and then redirects the request to the URL that was originally requested.
Modify the WebForm1.aspx page
The WebForm1.aspx page is the page that is requested originally. When the user requests this page, the request is redirected to the Logon.aspx page. After the request is authenticated, the request is redirected to the WebForm1.aspx page.
- In Solution Explorer, right-click WebForm1.aspx, and then click View Designer.
- Click the HTML tab in the Designer.
- Replace the existing code with the following code.
<%@ Page language="c#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Security.Principal" %>
<html>
<body>
<form id="Form1" method="post" runat="server">
<asp:Label ID="lblName" Runat=server /><br>
<asp:Label ID="lblAuthType" Runat=server />
</form>
</body>
</html>
<script runat=server>
void Page_Load(Object sender, EventArgs e)
{
lblName.Text = "Hello " + Context.User.Identity.Name + ".";
lblAuthType.Text = "You were authenticated using " + Context.User.Identity.AuthenticationType + ".";
}
</script>
- Save all files, and then compile the project.
- Request the WebForm1.aspx page. Notice that you are redirected to Logon.aspx.
- Type the logon credentials, and then click Submit. When you are redirected to WebForm1.aspx, notice that your user name appears and that LdapAuthentication is the authentication type for the Context.User.AuthenticationType property.
Note: Microsoft recommends that you use Secure Sockets Layer (SSL) encryption when you use Forms authentication. This is because the user is identified based on the authentication cookie, and SSL encryption on this application prevents anyone from compromising the authentication cookie and any other valuable information that is being transmitted.
请注意本文中代码由于使用了LDAP的API来访问域信息,所以一定要保证IIS所在的服务器也要在域环境中,否则使用LDAP的API来访问域信息时会被域服务器拒绝!
ASP.NET 中通过Form身份验证 来模拟Windows 域服务身份验证的方法的更多相关文章
- asp.net中通过form表单submit提交到后台的实例
前台<body>中的代码: <body> <div id="top"> </div> <form id="login ...
- ASP.NET中使用 Response.Write("<script>alert('****');</script>");后CSS界面发生变化的解决方法 (经验证)
在后台使用Response.Write("<script>alert('Hello World');</script>);弹出alert窗口后发现网页的界面和原来CS ...
- asp.net中常用的几种身份验证方式
转载:http://www.cnblogs.com/dinglang/archive/2012/06/03/2532664.html 前言 在B/S系统开发中,经常需要使用"身份验证&q ...
- ASP.NET查询页面设置form的action属性只弹出一个页面,并且每次将页面设置到最前
原文:ASP.NET查询页面设置form的action属性只弹出一个页面,并且每次将页面设置到最前 背景 当数据量大.查询条件复杂,多样多的时候,我们可能需要单独做一个查询界面,当用户选择设置了相关的 ...
- [转]asp.net5中使用NLog进行日志记录
本文转自:http://www.cnblogs.com/sguozeng/articles/4861303.html asp.net5中使用NLog进行日志记录 asp.net5中提供了性能强大的日志 ...
- asp.net5中使用NLog进行日志记录
asp.net5中提供了性能强大的日志框架,本身也提供了几种日志记录方法,比如记录到控制台或者事件中等,但是,对大部分程序员来说,更喜欢使用类似log4net或者Nlog这种日志记录方式,灵活而强大. ...
- 利用.net的内部机制在asp.net中实现身份验证
知识点: 在ASP.NET中,任何页面都是继承于System.Web.UI.Page,他提供了Response,Request,Session,Application的操作.在使用Visual Stu ...
- ASP.NET中身份验证
ASP.NET中身份验证有三种方式:Windows.Forms和Passport. 1.Windows验证,基于窗体验证,需要每个页面写上验证身份代码,相对灵活,但操作过于复杂: 2.Passport ...
- ASP.NET中身份验证的三种方法
Asp.net的身份验证有有三种,分别是"Windows | Forms | Passport",其中又以Forms验证用的最多,也最灵活.Forms 验证方式对基于用户的验证授权 ...
随机推荐
- SqlServer2008R2 如何插入多条数据
列id 为自增列 insert into Websites2values('Google','https://www.google.cm/','USA',1),('淘宝','https://www.t ...
- angularJs的工具方法
- $.ajax所犯的错误。success后面不执行
$.ajax({ type: 'post', url: '../AshxHandler/HandlerAddPhoto.ashx', data: { clientPath: photoName }, ...
- OC面向对象—多态
OC面向对象—多态 一.基本概念 多态是基于继承的基础之上的,多态可以使得父类的指针指向子类的对象.如果函数或参数中使用的是父类类型,可以传入父类.子类对象,但是父类类型的变量不能直接调用子类特有的方 ...
- 第五篇 Integration Services:增量加载-Deleting Rows
本篇文章是Integration Services系列的第五篇,详细内容请参考原文. 在上一篇你学习了如何将更新从源传送到目标.你同样学习了使用基于集合的更新优化这项功能.回顾增量加载记住,在SSIS ...
- javascript实例学习之四——javascript分页
话不多少,直接上代码 html代码: <!DOCTYPE html> <html lang="en"> <head> <meta char ...
- 审计参数 audit_trail
audit_trail参数定义了在哪里存放审计记录 默认是DB.如果将其设置为NONE,标准数据库审计功能被取消.audit_trail是静态参数,修改后必须重启数据库. 可以设置的值:- ...
- Unity3d UGUI 通用Confirm确认对话框实现(Inventory Pro学习总结)
背景 曾几何时,在Winform中,使用MessageBox对话框是如此happy,后来还有人封装了可以选择各种图标和带隐藏详情的MessageBox,现在Unity3d UGui就没有了这样的好事情 ...
- 解决Ueditor 不兼容IE7 和IE8
引用Ueditor的js 的时候用 绝对路径
- [转]10个顶级的CSS UI开源框架
随着CSS3和HTML5的流行,我们的WEB页面不仅需要更人性化的设计理念,而且需要更酷的页面特效和用户体验.作为开发者,我们需要了解一些宝贵的CSS UI开源框架资源,它们可以帮助我们更快更好地实现 ...