Skip to main content

How To: Use Forms Authentication with Active Directory in ASP.NET 2.0

This post will show you how to use forms authentication with Microsoft Active Directory directory service by using the ActiveDirectoryMembershipProvider.

To create a Web application with a logon page

  1. Start Microsoft Visual Studio® .NET development system, and then create a new ASP.NET Web site called FormsAuthAD.
  2. Use Solution Explorer to add a new Web form to the site called Login.aspx.
  3. Add a Login control to Login.aspx.

    By default, this control displays a user name field, a password field, and a Remember me next time checkbox. If the user selects this checkbox, a persistent authentication cookie is created and the user's browser stores the cookie on the user's computer.

    For security reasons, you should avoid creating persistent authentication cookies; therefore, disable this feature by setting the DisplayRememberMe property of the Login control to false.

    Note that when a user clicks Login on the Login control, it automatically validates the user by calling the configured membership provider, creates a forms authentication ticket, and then redirects the user back to the page he or she originally requested.

  4. If you are working in a test environment and have a service account with permissions to create new user accounts in Active Directory, add a CreateUserWizard control beneath the Login control so that users can register with your site and create new accounts.
    Note If you do not have the permissions to create new users, you will need to test authentication with an existing account.
You have to config your Web.Config with following settings

Locate the <authentication> element, and then change the mode attribute to Forms.

Add the following <forms> element as a child of the <authentication> element, and then set the name and timeout attributes as shown in the following example.

<authentication mode="Forms">

<forms name=".ADAuthCookie" timeout="10"/>

authentication>

<authorization>



Add the following <authorization> element beneath the <authentication> element in your Web.config file.

<authorization>

<deny users="?" />

<allow users="*" />

authorization>


Add configure ASP.Net for membership

In the Web.config file, add a connection string similar to the following, and modify it so that it points to your Active Directory users container.

<connectionStrings>

<add name="ADConnectionString" connectionString="LDAP://domainname"/>

connectionStrings>


Note The connection string shown above connects to the user's container within a domain called domainname. Update this string to point to the relevant users container within your domain.

Add a <membership> element after your <authorization> element, as shown in the following example.

<membership defaultProvider="MyADMembershipProvider">

<providers>

<add

name="MyADMembershipProvider"

type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

connectionStringName="ADConnectionString" attributeMapUsername="sAMAccountName"/>

providers>

membership>


Test Forms Authentication

Add a Page_Load Event Handler

Add the following code to the Page_Load event handler of your Default.aspx page. This page should be displayed only to authenticated users. To prove that this is the case, the code displays information obtained from the forms authentication ticket that is issued to authenticated users.

protected void Page_Load(object sender, EventArgs e)

{

Response.Write("Hello, " + Server.HtmlEncode(User.Identity.Name));

FormsIdentity id = (FormsIdentity)User.Identity;

FormsAuthenticationTicket ticket = id.Ticket;

Response.Write("

TicketName: "

+ ticket.Name);

Response.Write("
Cookie Path: "
+ ticket.CookiePath);

Response.Write("
Ticket Expiration: "
+

ticket.Expiration.ToString());

Response.Write("
Expired: "
+ ticket.Expired.ToString());

Response.Write("
Persistent: "
+ ticket.IsPersistent.ToString());

Response.Write("
IssueDate: "
+ ticket.IssueDate.ToString());

Response.Write("
UserData: "
+ ticket.UserData);

Response.Write("
Version: "
+ ticket.Version.ToString());

}

To logon as an existing user

  1. Browse to your application's Default.aspx page.

    The earlier configuration of the <authorization> element prevents unauthenticated users from accessing any pages in your application. They are redirected to your Login.aspx page.

  2. Enter valid credentials for an account in your domain, and then click Login.

    The format of the user name depends on the attributeMapUsername attribute of the <membership> element. The default configuration for the ActiveDirectoryMembershipProvider uses User Principal Names (UPNs) for name mapping as shown in the following example.

attributeMapUsername="userPrincipalName"

Because of this, all user names must have the format UserName@DomainName; for example: mary@testdomain.com or steve@testdomain.com.

You can change the name mapping so that it uses simple user name format by setting the following attribute in the Membership Provider configuration in the Web.config file.

attributeMapUsername="sAMAccountName"

This is how it is look like when you done with Web.Config.

<configuration>

<appSettings/>

<connectionStrings>

<add name="ADConnectionString" connectionString="LDAP://domainname"/>

connectionStrings>

<system.web>

<compilation debug="true"/>

<authentication mode="Forms">

<forms name=".ADAuthCookie" timeout="10"/>

authentication>

<authorization>

<deny users="?" />

<allow users="*" />

authorization>

<membership defaultProvider="MyADMembershipProvider">

<providers>

<add

name="MyADMembershipProvider"

type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

connectionStringName="ADConnectionString" attributeMapUsername="sAMAccountName"/>

providers>

membership>

system.web>

configuration>

Comments

Popular posts from this blog

Exit a T-SQL Cursor When Condition is met

Have you ever wanted to exit from a cursor when a condition is met? I wanted to do it. So this is how I did it. DECLARE @Field1 AS INT DECLARE @Field2 AS INT DECLARE CursorName CURSOR READ_ONLY FOR SELECT Field1, Field2 FROM TableName OPEN CursorName FETCH NEXT FROM CursorName INTO @Field1, @Field2 WHILE @@FETCH_STATUS = 0 BEGIN IF @Field1 = 1 BEGIN GOTO ENDCURSOR END FETCH NEXT FROM CursorName INTO @Field1, @Field2 END ENDCURSOR: CLOSE CursorName DEALLOCATE CursorName I have set my fonts to bold where you want to notice. So that's all I hope you will get something out of it and it is true that this is not a big deal. :)

Step by step guide to fix Angular app refresh issue in IIS

If you deploy your Angular app in IIS, routing will be handled from the client. So when you refresh a page it will give you 404 error. To get ride of the above-mentioned situation we have to follow the steps as follows: Before deploying anything on IIS, you have to install the URL Rewriting module on the IIS server. Please refer the link. After the installation, you should be seeing the following icon. If you are above to deploy an Angular app when is developed with ASP.Net Core. That deployment steps are explained in my previous blog post . That blog spot explains one issue I came across when I was deploying Angular 7 App with ASP.Net Core in IIS. So now we are done with IIS side installation next, we have to check the deployment files. You have to make sure that web.config file. web.config should contain the followings: <?xml version=”1.0" encoding=”UTF-8"?> <configuration> <system.webServer> <rewrite> <rules>

Generic Repository with Entity Framework Core

Recently I worked on a project with ASP.NET Core which uses Entity Framework Core. With them, I used a generic repository pattern in the data layer. Repository interface was like below: using System; using System.Collections.Generic; using System.Linq.Expressions; using OnlineSurvey.Models; namespace OnlineSurvey.Data { public interface IRepository<T> where T : BaseEntity { T GetById(int id, params Expression<Func<T, object>>[] includExpressions); void Add(T entity); void Delete(T entity); void Delete(int id); IEnumerable<T> GetAll(params Expression<Func<T, object>>[] includExpressions); IEnumerable<T> Find(Expression<Func<T, bool>> where); int Count(); } } And the implementation was like below: using System; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Collections.Generic; using Syste