Print
Add To Favorites
Email To Friend
Rate This Article
|
How to add a Login, Roles and Profile system to an ASP.NET 2.0 app in only 24 lines of code
|
Published:
18 Oct 2005
|
Abstract
In this article, Scott explore how to add a login, roles and profile system to an ASP.NET 2.0 application with the help of code samples. |
|
by Scott Guthrie
Feedback
|
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days):
32021/
46
|
|
|
Introduction |
Republished With Permission - Original Article
I’ve seen a few questions in the forums lately looking for
examples on how to use the CreateUserWizard control to create new users in the
ASP.NET 2.0 membership system, and then as part of the registration process
assign the new user into custom roles and/or collect and store custom profile
properties about them (country, address, gender, zipcode, etc).
Stefan from my team had a cool CreateUserWizard control
sample that I borrowed and expanded upon to build-up a sample that demonstrates
how to build a fairly common user management, roles and personalization system
in ASP.NET 2.0 that does this. I was pleasantly surprised to find it only took
about 25 lines of C# code in the entire app. J
The sample comes with 6 pages:
Figure 1
Specifically it supports:
1) Login support to enable registered users to login to the
web app using forms auth and the new membership system (login.aspx)
2) Registration support to enable visitors to create and
register new users in the membership system (CreateNewWizard.aspx)
3) Profile support that enables the site to gather
information about the user on registration, and for the users to see that
information on a profile page (MyProfile.aspx).
4) Change Password support to enable registered users to
change their password in the membership system (ChangePassword.aspx)
5) Password Recovery support to enable users to reset their
password if they forgot them (RecoverPassword.aspx)
You can download and run the sample yourself from here. Note
that it is built with the final release of VS 2005 and ASP.NET 2.0 – so it
won’t work with Beta2 (although it will probably work with the RC).
|
Implementation Notes on CreateNewWizard.aspx and MyProfile.aspx |
Only two of the above pages (CreateNewWizard.aspx and MyProfile.aspx)
have code in them. The others use the built-in Login controls in V2 to-do
everything (asp:login, asp:passwordrecovery, asp:changepassword).
CreateNewWizard.aspx is the most interesting page. It uses
the built-in <asp:createuserwizard> server control to-do most of the
heavy lifting and has two templated wizard steps defined within the wizard:
|
<asp:createuserwizard> wizard step 1: gathering
user-account data |
Figure 2
The <asp:createuserwizard> control handles gathering
up the user-account, email, password, and password recovery/answer data and
then calling into the ASP.NET 2.0 membership system to register the new user.
You simply have to override the control’s <createuserwizardstep> template
and customize the control layout to have things look how you want.
The sample is using the ASP.NET validation controls to
perform client-side validation on the inputs as well within the template
(example: making sure passwords match, the age is a valid integer, etc). One
added benefit in ASP.NET 2.0 is that these validation controls now support
client-side validation for FireFox and other modern browsers (note: all
screenshots were done using FireFox).
There are then three additional properties (their country,
gender and age) that I wanted to gather up about the new user as part of the
registration process. Doing this was pretty easy using the new ASP.NET 2.0
Profile system – simply add their definitions within the <profile> tag of
the web.config file to register them and store their values in the new profile
system:
Listing 1
<profile enabled="true">
<properties>
<add name="Country" type="string"/>
<add name="Gender" type="string"/>
<add name="Age" type="Int32"/>
</properties>
</profile>
I then handled the “CreatedUser” event on the
CreateUserWizard control within my CreateNewWizard.aspx.cs code-behind file to
retrieve the values from the controls within the CreateUserWizard control
template and set them in the profile store:
Listing 2
// CreatedUser event is called when a new user is successfully created
public void CreateUserWizard1_CreatedUser(object sender, EventArgs e) {
// Create an empty Profile for the newly created user
ProfileCommon p =
(ProfileCommon) ProfileCommon.Create(CreateUserWizard1.UserName, true);
// Populate some Profile properties off of the create user wizard
p.Country =
((DropDownList)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Country")).SelectedValue;
p.Gender =
((DropDownList)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Gender")).SelectedValue;
p.Age =
Int32.Parse(((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Age")).Text);
// Save profile - must be done since we explicitly created it
p.Save();
}
Because the user is being created as part of this step, I
explicitly choose to create a new Profile object in code (note that I was
passing in the CreatedUserWizard1.UserName property as the username – since the
user isn’t logged into the system yet). I then accessed the controls within
the template of the <asp:createuserwizard> control, pulled out their
values, and stuck them within the newly created profile. Calling p.save at the
end registered this profile with the new username. (Note: I’ll walk through
how we use this profile data later in a page below).
|
<asp:createuserwizard> wizard step 2: picking roles |
After the user fills out the first step of registration
information and clicks the next button, the user is created, the CreatedUser
event fires, and we fill in the appropriate information about the user into the
profile store.
The <asp:createuserwizard> control then displays the
second step template we’ve defined. This template lists all of the roles
currently created in the ASP.NET Role Management system, and allows the user to
select which roles they belong to:
Figure 3
Note that you’d typically never assign roles to an end-user
this way (instead you’d add your own logic to somehow calculate which role they
belong in), but I thought this scenario was cool nonetheless which is why it
works like the sample above.
I think it is cool because of the way we populate and access
these roles in the template of the <asp:createuserwizard>. Basically, we
have a template definition to the .aspx like this:
Listing 3
<asp:WizardStep runat="server" AllowReturn="False"
OnActivate="AssignUserToRoles_Activate"
OnDeactivate="AssignUserToRoles_Deactivate">
<table>
<tr>
<td>
Select one or more roles for the user:
</td>
</tr>
<tr>
<td>
<asp:ListBox ID="AvailableRoles" runat="server"
SelectionMode="Multiple" >
</asp:ListBox>
</td>
</tr>
</table>
</asp:WizardStep>
It simply contains a <asp:listbox> control named
“AvailableRoles”. When this wizard step is loaded (after the user hits the
next button on the first step in the wizard), it will fire the “OnActivate”
event. We can use this to databind the list of all roles in the system to the
above listbox. When the user hits next again, the wizard will fire the
“OnDeactivate” event. We can then use this to determine which roles were
selected in the above listbox, and use them to update the role-manager system.
The code to-do both of these actions looks like this:
Listing 4
// Activate event fires when user hits "next" in the CreateUserWizard
public void AssignUserToRoles_Activate(object sender, EventArgs e) {
// Databind list of roles in the role manager system to listbox
AvailableRoles.DataSource = Roles.GetAllRoles(); ;
AvailableRoles.DataBind();
}
// Deactivate event fires when user hits "next" in the CreateUserWizard
public void AssignUserToRoles_Deactivate(object sender, EventArgs e) {
// Add user to all selected roles from the roles listbox
for (int i = 0; i < AvailableRoles.Items.Count; i++) {
if (AvailableRoles.Items[i].Selected == true)
Roles.AddUserToRole(CreateUserWizard1.UserName, AvailableRoles.Items[i].Value);
}
}
That is all of the code for the CreateNewWizard.aspx.cs file
– 17 lines total if you omit comments and whitespace (if my count is right).
|
Next Step: Displaying User Profile Data |
The only other page in this scenario that required me to add
code was the MyProfile.aspx page. This page looks like this:
Figure 4
The page itself was pretty simple to implement. I simply
added a few asp:label controls on the page, as well a listbox for the roles.
Populating these controls with the profile and role information involved added
a Page_Load event with 7 lines of code like so:
Listing 5
protected void Page_Load(object sender, EventArgs e) {
Country.Text = Profile.Country;
Gender.Text = Profile.Gender;
Age.Text = Profile.Age.ToString();
RoleList.DataSource = Roles.GetRolesForUser(User.Identity.Name);
RoleList.DataBind();
}
Note that the profile object is strongly typed – which means
profile properties will get statement completion and compilation checking in VS
2005 with it. I can also then query the role management system to retrieve an
array of all the roles the current user belongs to and then databind this to
the listbox control.
Since the MyProfile.aspx page requires a user to be logged
in (otherwise retrieving profile information about them doesn’t make a lot of
sense), I also added a <location> based authorization control tag in my
web.config file:
Listing 6
<location path="MyProfile.aspx">
<system.web>
<authorization>
<deny users="?"/>
<allow users="*"/>
</authorization>
</system.web>
</location>
This is the same configuration I would have added in ASP.NET
V1.1 – and basically tells the system to deny all users who aren’t logged in
(the ? = anonymous), and then allow all users who are logged in (the * = all).
Those who aren’t logged in will get automatically
re-directed to the login.aspx page. The <asp:login> control can be used
there to allow users who have already registered to log-in without the
developer having to write any custom code.
|
Resources |
|
Summary |
Hopefully this walks-through a fairly common real-world web
app scenario and explains how it can be easily done in ASP.NET 2.0. The
ASP.NET 2.0 Membership, Role and Profile system (especially when combined with
the new login controls) pack a lot of productivity power.
What is really nice is that they are all built on the new
ASP.NET 2.0 provider model. Our of the box ASP.NET ships built-in providers
that provide Membership, Roles and Profile storage inside SQL Express, SQL
Server and Active Directory stores (the later for Membership and Roles only).
What is even better is that you can replace any of these implementations using
a custom provider that you either buy or build yourself (see this blog post for
more details on how to-do this). Replacing a provider in ASP.NET 2.0 simply
involves changing a value in a web.config file – the above code sample will
work regardless of what provider was plugged in (LDAP, Oracle, DB2, Custom SQL
Table Schema, File-System, etc).
Hope this helps,
Scott
|
|
|
User Comments
Title:
Thanks for the TRICK
Name:
Ankit Singhal
Date:
2009-12-20 3:05:23 PM
Comment:
Thanks a lot for such a wonderful idea.. it worked for me when used CreatedUser and FinishButtonClick Events in place of the Events u suggested. Great Idea. God Bless you :-)
|
Title:
problem!!!!!
Name:
avinash
Date:
2008-04-07 4:01:15 AM
Comment:
this code works fine with me in a public authorization folder! i need this code to make only role "admin" can create accounts so i placed it in a folder with admins only authorized! but the problem is that t creates the account but don't assign any role!! can any body help with this ?
|
Title:
Roles
Name:
Hossam
Date:
2007-07-11 3:47:45 AM
Comment:
this code works fine with me in a public authorization folder! i need this code to make only role "admin" can create accounts so i placed it in a folder with admins only authorized! but the problem is that t creates the account but don't assign any role!! can any body help with this ?
|
Title:
next step
Name:
dupls
Date:
2007-03-21 1:29:34 PM
Comment:
Is there any tutorial out there that will take this to the next level and place those details into another table in the database?
I've followed Scott through a zillion sites he is truly amazing. Very helpful code!
|
Title:
Ruler of the Universe
Name:
Rick
Date:
2007-03-08 7:39:47 PM
Comment:
Not too many comments here, but I think this is a fantastic soution. Thank you for sharing with us, Scott.
|
Title:
Mr
Name:
Pilling
Date:
2006-11-14 11:17:50 AM
Comment:
Anyone have the rolls bit in vb?
|
|
Product Spotlight
|
|