1. Introduction
In a web based environment, there is one common thing: user accounts. Not only have the user accounts, and also to provide authorization to access the particular modules. Providing user account support for a site involves the same set of steps: Creating a database table to store the user account information, creating a login page, maintain the logged on status is remembered across postbacks, specifying which pages are only available for authenticated users (authorization), maintain the password encryption / decryption, forgot password, change password. Prior to ASP.Net 2.0 the developers need to analyze how to implement all of these facets such as design the tables, and write the stored procedures, business and data access methods.
So, ASP.Net 2.0 has lightened the developers load by providing membership system, and the security Web controls built atop this API that make common user account tasks. There are two ways we could implement the Security features either by using ASP.NET 2.0 Web Controls or our customize code. In the Reference section, you could find the article where can you find the article to do Wizard process.
This article focuses on how programmatically use the Membership API and how it works in background in detail.
2. Membership:
2.1 Creating a database:
2.1 Creating a database:
Now, there is a database needed to store all the user personalized information. Wait..! Do we need to create the database for storing the information? Absolutely not. There are two ways to generate the database.
1. Use the ASP.NET Website Administration Tool (will create the database schema in a new SQL Server 2005 database file ASPNETDB.mdf, placed in the application's App_Data folder)
2. Use the ASP.NET SQL Server Registration Tool (aspnet_regsql.exe) command-line tool (use this tool to implement the schema in a SQL Server 2000 or 2005 database)
To use the ASP.Net Website Administration tool,
1. Open Visual Studio 2005 Website ASP.Net Configuration
2. Select the link “Use the security Setup Wizard to configure security step by step” which leads to configuration wizard page.
3. In Step 2, Select Access Method as “From the Internet”. By doing this will automatically create the database in your application’s App_Data folder named ASPNETDB.mdf which has the predefined schema.
If you would like to create the database in either SQL Server 2000 or SQL Server 2005, you can do the below:
1. Open Visual Studio 2005 Command Prompt
2. Type aspnet_regsql.exe is a tool which helps you to configure the database tables in relevant place on the server.
Well. Now, we have created the database called aspnetdb to store all the user credentials and membership role information.
Let’s dig into more detail on the database tables:
dbo.aspnet_Users - {UserName, UserID(GUID)}
dbo.aspnet_Membership - {UserID, Password} where UserID refers aspnet_Users table’s UserID.
dbo.aspnet_Roles - {RoleID, RoleName }
dbo.aspnet_UsersInRoles - {UserID, RoleID}
There are set of stored procedures are available to populate the above tables.
2.2 SqlMembership Provider Configurations:
The Membership API is implemented using the provider model, meaning that while the interface is well defined, the actual implementation can be customized.
SqlMembershipProvider stores user account information into above tables. Let see, How to configure SqlMembershipProvider into our application.
There are three important classes will be used to implement this feature.
- Membership
- Managing Users
- Working with lists of Users
User Statistics
- MembershipUser
- Managing Users in Roles
- Managing Roles
Roles
Determining whether User in a specific Role
These classes are available in System.Web.Security namespace.
Let see How programmatically accomplish these tasks.
2.3 Authentication using Membership:
2.3.1 Create User:
MembershipCreateStatus membershipCreateStatus;
MembershipUser newUser = null;
if (Membership.GetUser(userName) == null)
{
newUser = Membership.CreateUser(userName, password, email,
passwordQuestion, passwordAnswer, isApproved, out membershipCreateStatus);
}
The above step makes the entry in the database if the data is valid. Let see the possible output status which will get it from membershipCreateStatus.
- Success - 0
- DuplicateUserName
- DuplicateEmail
- InvalidPassword
- InvalidEmail
- InvalidQuestion
- InvalidAnswer
- InvalidUserName
- ProviderError
- UserRejected
So, these above are the possible output from MembershipCreateStatus out variable.
2.3.2 Authenicate the User:
By providing the username, and password the user can be validated by using the following method:
Membership.ValidateUser(userName, password);
The above method will return only Boolean value. So, how we can track the following things:
- The username might not be exist
- The username exist, but password might not exist
- The username and password may be correct, but:
- The user may not yet be approved
- The user may be locked out; this can happen if the user attempts to login with an invalid password for a specified number of tries. (five, by default which can be configured in web.config)
We can achieve above things by writing the below code:
MembershipUser membershipUser = Membership.GetUser(userName);
if (membershipUser == null)
{
//-- User does not exist.
}
else
{
if (membershipUser.IsApproved)
{
//-- User got approved.
}
else if (membershipUser.IsLockedOut)
{
//-- User is being locked.
}
else
{
//-- Password is incorrect
}
}
Well. So far we have seen how to create the user credentials, and how to evaluate it. But, if you would like to add Contact Number, First Name, and Last Name along with User account, Membership is not providing those features. mm. What to do?
Well .Net has the profile system to add other user related data. Let see in detail next section.
2.4 Authorization using Membership:
Authorizing the user is the next step Once the user gets authenticated into the system.
2.4.1 Create Role:
if (Roles.RoleExists(roleName) == false)
{
Roles.CreateRole(roleName);
}
Before adding a new role, let’s validate whether the role exists.
2.4.2 Add user to Role:
if (Roles.IsUserInRole(userName, roleName) == false)
{
Roles.AddUserToRole(userName, roleName);
}
Assign the user to the specified roles.
2.4.3 Remove the user from Role:
if (Roles.IsUserInRole(userName, roleName))
{
Roles.RemoveUserFromRole(userName, roleName);
}
The above code will remove the user from the roles, if there is an requirement to remove the user from set of roles, do the for each loop from the set, and call the above method.
2.4.4 Get the Roles for the User:
string[] rolesList = Roles.GetRolesForUser(userName);
This method will return the array of the roles.
2.4.5 Get all the Roles in the System:
string[] rolesList = Roles.GetAllRoles();
This method will return the array of the roles which are defined in the System.
2.4.6 Get all Users in the System:
MembershipUserCollection membershipUserCollection =
Membership.GetAllUsers();
This method will return the MembershipUser instances who are member in this System.
2.5 Profile System:
The Profile system is responsible for storing the additional user-specific information. The Profile system allows the page developer to define a set of "profile properties" in the Web.config file, and then needs to save and read those property values from some backing store upon request. The .NET Framework 2.0 ships with a SqlProfileProvider, which persists these user-specific properties to a denormalized database table. (namely, it squishes all of the profile property names and values into single columns in a database table).
dbo.aspnet_Profile stores the user specific information.
Columns:
UserID
PropertyNames
PropertyValues
The Values of these columns would be stored as by separating the colon.
SELECT * FROM dbo.aspnet_Profile
You could able to see the data by making a query above.
User GUID: encrypted data
PropertyNames:
ContactNumber:S:0:9:FirstName:S:9:7:LastName:S:16:8:
PropertyValuesString:
987654321StephenViswaraj
Any way, we do not worry about that how the SQL Server System retrieves and parsing. But, as a developer it is good to know how it works in background.
Once you compiled, the auto generated class will be created with class Name ProfileCommon which is inherited from System.Web.Profile.ProfileBase.
So, whatever the property has been defined in Web.Config will be generated as C# Code as below:
public virtual string ContactNumber
{
get {
return ((string)(this.GetPropertyValue("ContactNumber")));
}
set {
this.SetPropertyValue("ContactNumber", value);
}
}
Well. How to assign the values to these properties:
ProfileCommon profileCommon = (ProfileCommon)ProfileBase.Create(userName, true);
profileCommon.FirstName = firstName;
profileCommon.LastName = lastName;
profileCommon.ContactNumber = contactNumber;
profileCommon.Save();
That’s all. By making an instance of Profile Common class, we could able to access these properties. When the Save button gets clicked, the data will be updated into the table.
How to retrieve the values of these properties being assigned: Yes.
MembershipUser membershipUser = Membership.GetUser(userName);
if (membershipUser != null)
{
ProfileCommon profile = (ProfileCommon)ProfileBase.Create(membershipUser.UserName, true);
String UserName = membershipUser.UserName;
string FirstName = profile.FirstName;
string LastName = profile.LastName;
string ContactNumber = profile.ContactNumber;
http://www.4guysfromrolla.com/webtech/110701-1.shtml
A Multipart Series on ASP.NET 2.0's Membership, Roles, and Profile
http://aspnet.4guysfromrolla.com/articles/120705-1.aspx
No comments :
Post a Comment