8/9/2019 Litwin ASP Log in Controls and Security Nice
http://slidepdf.com/reader/full/litwin-asp-log-in-controls-and-security-nice 1/16
ASP.NET 2.0 Login Controlsand Security
Paul Litwin
Deep Training &Fred Hutchinson Cancer Research Center
Paul Litwin• Developer
? Focus: ASP.NET, ASP, VB, C#, SQL Server, …
? MCSD
? Microsoft MVP
? Programming Mngr with Fred Hutchinson Cancer ResearchCenter
• Co-Founder and Senior Trainer? Deep Training
• www.deeptraining.com
• Conference Chair/Speaker? Chair, Microsoft ASP.NET Connections
? Member INETA Speakers Bureau
• Author? Author/co-author of a dozen books, including…
• ASP.NET for Developers
• Access Cookbook, 2 nd edition • Access 2002 Desktop/Enterprise Dev Handbook
8/9/2019 Litwin ASP Log in Controls and Security Nice
http://slidepdf.com/reader/full/litwin-asp-log-in-controls-and-security-nice 2/16
Slides & Samples Download
• You can download them from:
? www.deeptraining.com/litwin
Agenda
• New Provider-Based APIs
• ASP.NET 2.0 Security Highlights
• Security Setup Wizard
• Login Controls
• Membership Service
• Role Service
8/9/2019 Litwin ASP Log in Controls and Security Nice
http://slidepdf.com/reader/full/litwin-asp-log-in-controls-and-security-nice 3/16
8/9/2019 Litwin ASP Log in Controls and Security Nice
http://slidepdf.com/reader/full/litwin-asp-log-in-controls-and-security-nice 4/16
Provisioning Application Databaseand Un-Hardwiring SQLExpress (2 of 3)
1. Run aspnet_regsql command-line tool to startASP.NET SQL Server Setup Wizard
a) On 2nd page, select Configure SQL Server forApplication Services
b) On the next page, specify your database server
name and <default> for database
(only need to do step #1 once per SQL Server)
2. From Visual Studio, add a new web.config file
to the site (if it's not already there)
Provisioning Application Databaseand Un-Hardwiring SQLExpress (3 of 3)
3. Replace the empty <connectionStrings/> elementwith (for example if SQL Server is on localhost):
Note: unless you plan on tweaking the machine.config or creating a new provider you need to stick with the LocalSqlServer name which the AspNetSqlProfileProvider is expecting to see.
<connectionStrings>
<remove name="LocalSqlServer"/>
<add name="LocalSqlServer"
connectionString="Data Source=localhost;
Initial Catalog=aspnetdb;Integrated Security=True"
providerName="System.Data.SqlClient" /></connectionStrings>
<connectionStrings>
<remove name="LocalSqlServer"/>
<add name="LocalSqlServer"
connectionString="Data Source=localhost;
Initial Catalog=aspnetdb;Integrated Security=True"
providerName="System.Data.SqlClient" /></connectionStrings>
8/9/2019 Litwin ASP Log in Controls and Security Nice
http://slidepdf.com/reader/full/litwin-asp-log-in-controls-and-security-nice 5/16
Providers
ASP.NET Whidbey “Building Block” APIs
MembershipMembership
Windows SQL Server Custom
Role ManagerRole Manager PersonalizationPersonalization
Site NavigationSite Navigation Database CachingDatabase Caching ManagementManagement
Provider Model Design Pattern
Access MDB
ASP.NET 2.0 Provider-Based APIs
2.0 Security Highlights (1 of 2)• Forms Authentication
? Cookieless authentication now supported
• Login Controls
? UI controls for managing login of users
• Membership
? Standardized solution for storing formsauthentication data
? Membership.ValidateUser method
? Login controls wrap up membership service
? Provider-based
8/9/2019 Litwin ASP Log in Controls and Security Nice
http://slidepdf.com/reader/full/litwin-asp-log-in-controls-and-security-nice 6/16
8/9/2019 Litwin ASP Log in Controls and Security Nice
http://slidepdf.com/reader/full/litwin-asp-log-in-controls-and-security-nice 7/16
Using Security Setup Wizard
• Walks you throughsetting upauthentication,membership provider,users, and rolemanagement for Website
• Can setup Forms orWindows auth
• Start wizard from Web
Site Admin Tool(Website | ASP.NETConfiguration)
Login ControlsBuilt on top of Membership & Role APIs
• Login – log in users (goes on login page)
• LoginView – displays different viewsbased on whether user is authenticatedand what roles they are member of
• PasswordRecovery – recover or reset lostpassword
• LoginStatus – displays login or logout link
• LoginName – displays login name forauthenticated users
• CreateUserWizard – steps user through wizard tocreate new account
• ChangePassword – changes password for user
• All the login controls can be templated
8/9/2019 Litwin ASP Log in Controls and Security Nice
http://slidepdf.com/reader/full/litwin-asp-log-in-controls-and-security-nice 8/16
Demo
• Building a Site using the Login controls
Login Controls Tips and Tricks
8/9/2019 Litwin ASP Log in Controls and Security Nice
http://slidepdf.com/reader/full/litwin-asp-log-in-controls-and-security-nice 9/16
Working with Login Control Templates
• Every login control supports conversion totemplates for customization
• For Example: Let’s say you need to verify a user
is a member (e.g., has a valid AuthorId beforeyou allow them to create a login account)
? Select Customize the CreateUser Step command fromCreateUserWizard tasks
? Example:NewUserCustom.aspx
Verifying Authors in Pubs dbNewUserCustom.aspx
protected void cuwAuthor_CreatingUser(object sender, LoginCancelEventArgs e){
if (Page.IsValid){
TextBox txtAuthorId = (TextBox)cuwAuthor.CreateUserStep.ContentTemplateContainer.FindControl("txtAuthorId");
Label lblError = (Label)cuwAuthor.CreateUserStep.ContentTemplateContainer.FindControl("lblError");
bool boolOk = Author.ValidateAuthorId(txtAuthorId.Te xt);
if (!boolOk){
lblError.Text = "No matching author id was found. " +"Please ensure that you have entered the number correctly.";
e.Cancel = true;}
}}
protected void cuwAuthor_CreatingUser(object sender, LoginCancelEventArgs e){
if (Page.IsValid){
TextBox txtAuthorId = (TextBox)cuwAuthor.CreateUserStep.ContentTemplateContainer.FindControl("txtAuthorId");
Label lblError = (Label)cuwAuthor.CreateUserStep.ContentTemplateContainer.FindControl("lblError");
bool boolOk = Author.ValidateAuthorId(txtAuthorId.Te xt);
if (!boolOk){
lblError.Text = "No matching author id was found. " +"Please ensure that you have entered the number correctly.";
e.Cancel = true;}
}}
8/9/2019 Litwin ASP Log in Controls and Security Nice
http://slidepdf.com/reader/full/litwin-asp-log-in-controls-and-security-nice 10/16
Logging Login Activity
Login.aspx
protected void lgUser_LoggedIn(object sender, EventArgs e){
Logging.LogActivity(lgUser.UserName,
Page.Request.Url.ToString(),Page.Request.UserHostAddress,"Login success");
}protected void lgUser_LoginError(object sender, EventArgs e)
{Logging.LogActivity(
lgUser.UserName,
Page.Request.Url.ToString(),Page.Request.UserHostAddress,
"Login failure");}
protected void lgUser_LoggedIn(object sender, EventArgs e){
Logging.LogActivity(lgUser.UserName,
Page.Request.Url.ToString(),Page.Request.UserHostAddress,"Login success");
}protected void lgUser_LoginError(object sender, EventArgs e)
{Logging.LogActivity(
lgUser.UserName,
Page.Request.Url.ToString(),Page.Request.UserHostAddress,
"Login failure");}
Customizing Login Rules
• Override AspNetSqlMembershipProvider
<membership><providers><clear/><add name="AspNetSqlMembershipProvider"type="System.Web.Security.SqlMembershipProvider, System.We b,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"connectionStringName="AspnetCnxString"
enablePasswordRetrieval="false" enablePasswordReset="true"requiresQuestionAndAnswer="true"applicationName="marscg" requiresUniqueEmail="true"passwordFormat="Hashed" maxInvalidPasswordAttempts="5"minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0"passwordAttemptWindow="10" passwordStrengthRegularExpression=""/>
</providers></membership>
<membership><providers><clear/><add name="AspNetSqlMembershipProvider"type="System.Web.Security.SqlMembershipProvider, System.We b,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"connectionStringName="AspnetCnxString"
enablePasswordRetrieval="false" enablePasswordReset="true"requiresQuestionAndAnswer="true"applicationName="marscg" requiresUniqueEmail="true"passwordFormat="Hashed" maxInvalidPasswordAttempts="5"minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0"passwordAttemptWindow="10" passwordStrengthRegularExpression=""/>
</providers></membership>
8/9/2019 Litwin ASP Log in Controls and Security Nice
http://slidepdf.com/reader/full/litwin-asp-log-in-controls-and-security-nice 11/16
Membership Service• Saves you from having to manage users and
passwords• Login controls may obviate need to directly work with
the classes in many cases
• Choice of providers (SQL Server, Access, etc.)
• Example Uses? Authenticate User
• Membership.ValidateUser()
? Find User by Email address• Membership.FindUsersByEmail()
? Estimate number of users online
• Membership.GetNumberOfUsersOnline()• Example: MasterPage.master
Role Service
• Simplifies authorization using roles
• Manage roles at design time using ASP.NETWeb Admin tool
? Or use Roles and RoleProvider classes at runtime
• Use LoginView control to display custom
content per role? Order RoleGroup elements from highest to lowest
precedence (e.g., Admin first, etc.)
• Or use User.IsInRole() method from code
8/9/2019 Litwin ASP Log in Controls and Security Nice
http://slidepdf.com/reader/full/litwin-asp-log-in-controls-and-security-nice 12/16
Role Service
• Role data carried between pages by ASP.NETusing encrypted cookies
• Reduces round-trips to database for role
information
LoginView Roles ExampleSecureSite/ LoginView.aspx
<asp:LoginView ID="lvRoles" Runat="server"><RoleGroups>
<asp:RoleGroup Roles="Admins"><ContentTemplate>This message prints for members of Admins group.</ContentTemplate></asp:RoleGroup><asp:RoleGroup Roles="Managers"><ContentTemplate>This message prints for members of Managersgroup.
</ContentTemplate></asp:RoleGroup><asp:RoleGroup Roles="Users"><ContentTemplate>This message prints for members of Users group.</ContentTemplate></asp:RoleGroup>
</RoleGroups></asp:LoginView>
<asp:LoginView ID="lvRoles" Runat="server"><RoleGroups>
<asp:RoleGroup Roles="Admins"><ContentTemplate>This message prints for members of Admins group.</ContentTemplate></asp:RoleGroup><asp:RoleGroup Roles="Managers"><ContentTemplate>This message prints for members of Managersgroup.
</ContentTemplate></asp:RoleGroup><asp:RoleGroup Roles="Users"><ContentTemplate>This message prints for members of Users group.</ContentTemplate></asp:RoleGroup>
</RoleGroups></asp:LoginView>
8/9/2019 Litwin ASP Log in Controls and Security Nice
http://slidepdf.com/reader/full/litwin-asp-log-in-controls-and-security-nice 13/16
IsInRole Roles ExampleSecureSite/ RoleMembership.aspx.vb
Sub Page_Load()' Order by highest to lowest
If User.IsInRole("Admins") ThenlblRole.Text = "Administrator"
ElseIf User.IsInRole("Managers") ThenlblRole.Text = "Manager"
ElseIf User.IsInRole("Users") ThenlblRole.Text = "User"
Else
lblRole.Text = "Not logged in."End IfEnd Sub
Sub Page_Load()' Order by highest to lowest
If User.IsInRole("Admins") ThenlblRole.Text = "Administrator"
ElseIf User.IsInRole("Managers") ThenlblRole.Text = "Manager"
ElseIf User.IsInRole("Users") ThenlblRole.Text = "User"
ElselblRole.Text = "Not logged in."
End IfEnd Sub
Adding New Users to a RoleNewUserCustom.aspx
protected void cuwAuthor_CreatedUser(object sender, EventArgs e){
TextBox txtUserName =(TextBox)cuwAuthor.CreateUserStep.
ContentTemplateContainer.FindControl("UserName");Roles.AddUserToRole(txtUserName.Text, "Users");
}
protected void cuwAuthor_CreatedUser(object sender, EventArgs e){
TextBox txtUserName =(TextBox)cuwAuthor.CreateUserStep.
ContentTemplateContainer.FindControl("UserName");Roles.AddUserToRole(txtUserName.Text, "Users");
}
8/9/2019 Litwin ASP Log in Controls and Security Nice
http://slidepdf.com/reader/full/litwin-asp-log-in-controls-and-security-nice 14/16
Branching at Login Based on Role Membership
Login.aspx
protected void lgUser_LoggedIn(object sender, EventArgs e){
if (Roles.IsUserInRole(lgUser.UserName, "Admins") ||Roles.IsUserInRole(lgUser.UserName, "Developers"))
{Response.Redirect("~/Admin/Admin.aspx");
}
else{
Response.Redirect("~/Default.aspx");}
}
protected void lgUser_LoggedIn(object sender, EventArgs e){
if (Roles.IsUserInRole(lgUser.UserName, "Admins") ||Roles.IsUserInRole(lgUser.UserName, "Developers"))
{Response.Redirect("~/Admin/Admin.aspx");
}
else{
Response.Redirect("~/Default.aspx");}
}
Security Trimming
• When using site maps, you can
automatically have the site map adjustedby role membership
• Works with access rules
<siteMap defaultProvider="XmlSiteMapProvider"
enabled="true"><providers>
<add name="XmlSiteMapProvider"description="Default SiteMap provider."
type="System.Web.XmlSiteMapProvider"
siteMapFile="Web.sitemap"securityTrimmingEnabled="true" />
</providers>
</siteMap>
<siteMap defaultProvider="XmlSiteMapProvider"
enabled="true"><providers>
<add name="XmlSiteMapProvider"description="Default SiteMap provider."
type="System.Web.XmlSiteMapProvider"
siteMapFile="Web.sitemap"securityTrimmingEnabled="true" />
</providers>
</siteMap>
8/9/2019 Litwin ASP Log in Controls and Security Nice
http://slidepdf.com/reader/full/litwin-asp-log-in-controls-and-security-nice 15/16
Personalization Service
• No need to create fields in a database tokeep track of personalization data
• Allows you to strongly type your
personalization data
• You maintain personalization data in userprofiles
Creating a ProfileSecureSite/ web.config
<profile><properties>
<add name="sex" type="System.String"/><add name="age" type="System.Int32"/>
<add name="color" type="System.String"/><add name="birthdate" type="System.DateTime"/>
</properties></profile>
<profile><properties>
<add name="sex" type="System.String"/><add name="age" type="System.Int32"/>
<add name="color" type="System.String"/><add name="birthdate" type="System.DateTime"/>
</properties></profile>
8/9/2019 Litwin ASP Log in Controls and Security Nice
http://slidepdf.com/reader/full/litwin-asp-log-in-controls-and-security-nice 16/16
Reading/Writing Profile DataSecureSite/ThemedPage.aspx
Profile.color = ddlColor.SelectedValue;
fOk = Int32.TryParse(txtAge.Text,out intTryAge);
if (fOk)Profile.age = intTryAge;
elseProfile.age = -1;
Profile.color = ddlColor.SelectedValue;
fOk = Int32.TryParse(txtAge.Text,out intTryAge);
if (fOk)Profile.age = intTryAge;
elseProfile.age = -1;
Thank You!
•Please complete evaluation forms
•Contact: [email protected]
•Download slides & samples from
?www.deeptraining.com/litwin