Introduction
After reading this article, you will be able to perform the following tasks. To speed up the performance of membership provider, don't forget to read Omar Al Zabir's post. It will help you to work on SQL hints like nolock, readpast, etc. and you will successfully resolve the issues regarding tablelocks or transaction dead locks.- Setup ASP.NET Membership provider database using Microsoft SQL server 2005
- Create user
- Create Role Add user in Role
- Provider Role based security to your application
- Redirecting authorized users to see his web section to which he is authorized to see
- Password recovery control and configuration.
- Single Sign in / single login / single signin
For NLB network load balancing, refer to west-wind.
Steps
- Open ASPnet_RegSQL.exe and Run $:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regsql.exe.
Note** $ is your root driver where windows is installed.
Alternatively, you can open .NET command prompt and runaspnet_regSQL.
- The opened wizard will guide you through the rest of the setup.
Select your DB where you would like to install wizard tool which will generate ASP.NET membership provider Tables, views and stored procedures automatically in your DB.
- Create new ASP.NET web site using C# language as a code behind.
Add Web.Config file to your web application. It will look like this as shown below:
<?xml version="1.0"?> <configuration> <appSettings/> <connectionStrings/> <system.web> <compilation debug="false" /> <authentication mode="Windows" /> </system.web> </configuration>
- The opened wizard will guide you through the rest of the setup.
Select your DB where you would like to install wizard tool which will generate ASP.NET membership provider Tables, views and stored procedures automatically in your DB.
- Configure Membership provider in web.config.
First, we will add connection string to the database where we have
created aspnet database and tell the provider to use that using
connectionStringName.
<connectionStrings> <add name="aspnetdbConnectionString" connectionString="Data Source=;Initial Catalog=; Persist Security Info=True;User ID=;Password=" providerName="System.Data.SqlClient" /> </connectionStrings>
- Use Forms authentication:
<authentication mode="Forms" > </authentication>
- Set Forms authentication Cookie name, Redirect to Login path and Default path:
<compilation debug="false" /> <authentication mode="Forms" > <forms defaultUrl="default.aspx" name="myform" timeout="5" loginUrl="~/login.aspx" slidingExpiration="true" > </forms> </authentication>
- Add
Membershiptag in web.config. Take a closer look at the bold words:<membership defaultProvider="xyzMembershipProvider"> <providers> <clear/> <add name="xyzMembershipProvider" type="System.Web.Security.SqlMembershipProvider" applicationName="/myApp" connectionStringName="aspnetdbConnectionString"/> </providers> </membership>
Don't forget to addapplicationNameattribute in yourmembershipprovider, otherwise it will generateGUIDinaspnet_Applicationstable.
Note**: Now your web application is ready to use built in login controls.
Drag and Drop
- Create user Wizard
- Login status
- Login control to see how it works
Here is the code snippet. It will help you while migrating your existing user management system to ASP.NET provider based membership management.
protected void Button1_Click(object sender, EventArgs e) { MembershipCreateStatus status; MembershipUser user = Membership.CreateUser ("Satalaj","P@ssw0rd",satalajmore-aspnet@yahoo.co.in, "Who am I ?","Satalaj",true,out status); switch(status) { case MembershipCreateStatus.DuplicateUserName: Response.Write("User already exists in system. Please select different name and try again"); break; case MembershipCreateStatus.DuplicateEmail : Response.Write("Duplicate Email"); break; case MembershipCreateStatus.Success : Response.Write("User has been created successfully"); break; } }
- Use Forms authentication:
- Create Role if Role doesn't exist in the system:
protected void Button2_Click(object sender, EventArgs e) { if(!Roles.RoleExists("Editor")) { Roles.CreateRole("Editor"); } }
- Add user into Editor Role if he is not in that role.
protected void Button3_Click(object sender, EventArgs e) { if(!Roles.IsUserInRole("satalaj","Editor")) { Roles.AddUserToRole("satalaj","Editor"); } }
- Add user into Editor Role if he is not in that role.
- How to prevent anonymous users from accessing Folder contents of Editor.
Now we will add a new folder called editor and we will authorize only users who are in Editor role to view the contents of that folder. To do that, add the below web.config file into editor folder.
Note**: Whatever you put inside this Editor folder will be available to only logged in users. To do that, we added web.config file in it as shown below:
<?xml version="1.0"?> <configuration> <appSettings/> <connectionStrings/> <system.web> <authorization> <deny users="?"/> <allow roles="Editor"/> </authorization> </system.web> </configuration>
- Login user and redirect logged in user to his authorized section based on his roles:
protected void Button4_Click(object sender, EventArgs e) { if(Membership.ValidateUser("satalaj",P@ssw0rd)) { FormsAuthentication.SetAuthCookie("satalaj",true); if(Roles.IsUserInRole("satalaj","Editor")) { Response.Redirect("~/Editor/manageArticles.aspx"); } } }
Put some .pdf file init, say sat.pdf is located in Editor and try to access in browser http://yourapplication/Editor/sat.pdf.
If you are authenticated and your role is Editor, then you will be able to access this sat.pdf.
Now clear cookies and try to authenticate without login, you will be redirected to login page.
Next, we will see how to configure password recovery control and email configuration.
- To configure your Password recovery control, add the below tag in your web.config.
<system.net> <mailSettings> <smtp from="satalaj@sat.com"> <network host="smtp.server.address.com" port="25" userName="mysmtpUserName@smtp.com" password="password"/> </smtp> </mailSettings> </system.net>
Drag and drop Password recovery control into your web.config.
If you want to configure smtp.gmail.com with password recovery control, then follow the steps given by me at http://forums.asp.net/t/1250771.aspx?PageIndex=1.
After configuring your email settings, take a look at web.config. It should look like the below one:
<?xml version="1.0"?> <configuration> <appSettings/> <connectionStrings> <add name="aspnetdbConnectionString" connectionString="Data Source=;Initial Catalog=; Persist Security Info=True;User ID=;Password=" providerName="System.Data.SqlClient"/> </connectionStrings> <system.web> <compilation debug="true"/> <authentication mode="Forms"> </authentication> <membership defaultProvider="xyzMembershipProvider"> <providers> <clear/> <add name="xyzMembershipProvider" type="System.Web.Security.SqlMembershipProvider" applicationName="/myApp" connectionStringName="aspnetdbConnectionString"/> </providers> </membership> <roleManager enabled="true" defaultProvider="xxxRoleManagerProvider"> <providers> <add name="xxxRoleManagerProvider" type="System.Web.Security.SqlRoleProvider" applicationName="/myApp" connectionStringName="aspnetdbConnectionString"/> </providers> </roleManager> </system.web> <system.net> <mailSettings> <smtp from="satalaj@sat.com"> <network host="smtp.server.address.com" port="25" userName="mysmtpUserName@smtp.com" password="password"/> </smtp> </mailSettings> </system.net> </configuration>
For more information about the tags and code, visit http://msdn.microsoft.com/en-us/library/ms998347.aspx.
- Single sign in
If you want two users not to sign in using the same credentials, then it can be avoided using the below code:
MembershipUser user = Membership.GetUser(login1.UserName); if (user.IsOnline) { //cancel login...redirect to not allowed page }
In web.config membership tag, add attributeuserIsOnlineTimeWindow= 1. If theLastActivityDatefor a user is greater than the current date and time minus theUserIsOnlineTimeWindowvalue in minutes, then the user is considered online.
Example:
<membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="1"> <providers> <add name="SqlProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="SqlServices" enablePasswordRetrieval="true" enablePasswordReset="false" requiresQuestionAndAnswer="true" passwordFormat="Encrypted" applicationName="MyApplication" /> </providers> </membership>
No comments:
Post a Comment