A) Create the login form 1. On the login.aspx page create a login form with the
ID: 3664662 • Letter: A
Question
A) Create the login form
1. On the login.aspx page create a login form with the following fields using asp.net web controls. Name the ID of the fields with something self-documenting: txtusername,
txtpassword, txtrole and btnsubmit a. username - textbox b. password - textbox c. role – radiobuttonlist (admin, member, user are the three roles with guest as the
default) d. submit button (that says Click here to login)
2. Use validation controls on the form to make sure they filled out the text boxes and a role.
B) Process the Form
1. Open and edit the C# code file, login.aspx.cs. 2. In the submit button event handler event handler, process the form
a. Retrieve the values from the login form. b. If they are empty, display an error message c. If they are not empty, continue. d. Determine if the role information matches on of these: roles: admin e. If yes, then determine if the information matches on of these: names, passwords
a. admin Janet wildberry^8324
b. admin Jullian rainbowClear(8812)
f. If they do not match, stay on the page and display an error message
g. If the username and password match one of the options above, they are a valid user so you can continue with the additional coding.
C) Create session variables and cookies and Use Server-Side Redirection Methods To Redirect The User To Another Location
Note that normally we don’t store passwords in sessions… it’s a security issue! This is just to show that you know how to store ‘something’ in a session and what sessions are.
a. Create the session variables in the login.aspx.cs page (continue from the previous step)
Username in Username.
Session["UserName"] = Email.Text;
Rassword in Password. Role in Role. Last name in LastName First name in FirstName Last Current date in LastVisited IP address from the server variables IPAddress User Agent string from the server variables in UserAgent Browser Information from the Browser Object in BrowserInfo
Request.Browser.Browser.ToString()
b. Create the cookies
Create a group cookie named UserInfo which sill store all the cookie values with one expiration date. In the cookie collection store the following cookies: 1. Set the individual cookie named to the session variable name from
above.
Response.Cookies["UserInfo"]["UserName"] = Session["UserName"].ToString();
2. Set the individual cookie values to the corresponding session values. 3. Set the expiration date for one year from today.
Response.Cookies["UserInfo"].Expires = DateTime.Now.AddYears(1);
Refer to the lesson and https://msdn.microsoft.com/en-us/library/ms178194(v=vs.140).aspx for additional help on reading the cookies
c. The user is now officially logged in. Use Server.Transfer to redirect them to the success.aspx page
Explanation / Answer
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Security;
protected void ValidateUser(object sender, EventArgs e)
{
int userId = 0;
string roles = string.Empty;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Validate_User"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Username", Login1.UserName);
cmd.Parameters.AddWithValue("@Password", Login1.Password);
cmd.Connection = con;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
userId = Convert.ToInt32(reader["UserId"]);
roles = reader["Roles"].ToString();
con.Close();
}
switch (userId)
{
case -1:
Login1.FailureText = "Username and/or password is incorrect.";
break;
case -2:
Login1.FailureText = "Account has not been activated.";
break;
default:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, Login1.UserName, DateTime.Now, DateTime.Now.AddMinutes(2880), Login1.RememberMeSet, roles, FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
if (ticket.IsPersistent)
{
cookie.Expires = ticket.Expiration;
}
Response.Cookies.Add(cookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(Login1.UserName, Login1.RememberMeSet));
break;
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
if (this.Page.User.Identity.IsAuthenticated)
{
FormsAuthentication.SignOut();
Response.Redirect("~/Login.aspx");
}
}
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new GenericPrincipal(id, roles);
}
}
}
}
HTML MARKUP
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
<style type="text/css">
body{font-family: Arial;font-size: 10pt;}
.main_menu{width: 100px; background-color: #fff;border: 1px solid #ccc !important; color: #000;text-align: center;height: 30px;line-height: 30px;margin-right: 5px;}
.level_menu{width: 110px; background-color: #fff; color: #333;border: 1px solid #ccc !important;text-align: center;height: 30px;line-height: 30px;margin-top: 5px;}
.selected{background-color: #9F9F9F;color: #fff;}
input[type=text], input[type=password]{width: 200px;}
table{border: 1px solid #ccc;}
table th { background-color: #F7F7F7;color: #333;font-weight: bold;}
table th, table td { padding: 5px; border-color: #ccc; }
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:LoginView ID="LoginView" runat="server">
<LoggedInTemplate>
<div align="right">
Welcome <asp:LoginName ID="LoginName1" runat="server" Font-Bold="true" />
<br /><br />
<asp:Label ID="lblLastLoginDate" runat="server" />
<asp:LoginStatus ID="LoginStatus1" runat="server" />
</div>
<hr />
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" ShowStartingNode="false"
SiteMapProvider="SiteMap" />
<asp:Menu ID="Menu" runat="server" DataSourceID="SiteMapDataSource1" Orientation="Horizontal"
>
<LevelMenuItemStyles>
<asp:MenuItemStyle CssClass="main_menu" />
<asp:MenuItemStyle CssClass="level_menu" />
</LevelMenuItemStyles>
</asp:Menu>
</LoggedInTemplate>
</asp:LoginView>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
XML
<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNodeurl="" title="Home" description="" roles ="*">
<siteMapNode url="~/Home.aspx" title="Home" description="Home Page" roles="*" />
<siteMapNode url="javascript:;" title="Admin" description="Admin Page" roles ="Administrator">
<siteMapNode url ="~/Admin/Users.aspx" title="Users" description="Users Page"></siteMapNode>
<siteMapNode url ="~/Admin/Reports.aspx" title="Reports" description="Reports Page"></siteMapNode>
</siteMapNode>
<siteMapNode url="~/Contact.aspx" title="Contact" description="Contact Us Page" roles="*" />
</siteMapNode>
</siteMap>
<configuration>
<connectionStrings>
<add name="constr" connectionString="Data Source=.SQL2005;Initial Catalog=LoginDB;user id=sa;password=password;"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<authentication mode="Forms">
<forms defaultUrl="~/Home.aspx" loginUrl="~/Login.aspx" slidingExpiration="true" timeout="2880"></forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
<siteMap enabled ="true" defaultProvider="SiteMap">
<providers>
<add name="SiteMap" type="System.Web.XmlSiteMapProvider" siteMapFile="~/Web.sitemap" securityTrimmingEnabled="true" />
</providers>
</siteMap>
</system.web>
</configuration>
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.