I seem to cant set up an authentication system in asp.net
I have code for a login system:
protected void btnlogin_Click(object sender, EventArgs e)
{
PageUser myUser = new PageUser();
if (myUser.AuthenticateUser(txtUsername.Text, txtPassword.Text))
{
// entry found
HttpCookie myCookie;
DateTime now = DateTime.Now;
myCookie = new HttpCookie("UserName");
myCookie.Value = myUser.UserName;
myCookie.Expires = now.AddMinutes(30);
Response.Cookies.Add(myCookie);
myCookie = new HttpCookie("LoginID");
myCookie.Value = myUser.UserLoginID.ToString();
myCookie.Expires = now.AddMinutes(30);
Response.Cookies.Add(myCookie);
lblResult.Visible = false;
FormsAuthentication.SetAuthCookie(myUser.UserName + " " + myUser.UserLoginID.ToString(), true);
Response.Redirect("AdminView.aspx");
}
else
{
// entry not found
lblResult.Text = "<b>Invalid logon attempt<b>";
lblResult.ForeColor = System.Drawing.Color.FromName("Red");
lblResult.Visible = true;
}
}
The authentication method works fine, but when I do not login it still lets me redirect twords the AdminView even though the person didnt login.
Code I am having difficulty with:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
string userName = "";
string[] splits;
try
{
if (this.Page.User.Identity.IsAuthenticated)
{
splits = this.Page.User.Identity.Name.Split(new char[1] { ' ' });
userName = splits[0] + " " + splits[1];
}
else
{
Response.Redirect("default.aspx");
}
txtLoggedInUser.Text += " - " + userName;
}
catch
{
Response.Redirect("default.aspx");
}
}
I am not sure how to write this code so it would redirect a person back to the login page when they try to visit the admin page.
To restrict an unauthenticated user to the
AdminView.aspxpage, you have to add below into theconfigurationsection of theweb.configfile.<deny users="?"/>mean’s theunauthenticateduser will not be able to access the file/folderAdminView.aspx