Here login and logout buttons in master page. In login page is using FormsAuthenticationTicket and HttpCookie, so in master page I want to check the forms authentication and then display logout if is authenticated and hide login. If not authenticated display login and hide logout. How can I do that?
Login:
com.CommandText = "select [id], [username],[password], [type] FROM [users] WHERE [username] =@username AND [password]= @pass";
com.Parameters.AddWithValue("@username", UserName.Text);
com.Parameters.AddWithValue("@pass", Password.Text);
// conn.Open();
SqlDataReader rd = com.ExecuteReader();
if (rd.Read())
{
var _id = rd["id"].ToString();
var _fname = rd["username"].ToString();
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
_id,
DateTime.Now,
DateTime.Now.AddMonths(1),
true,
"." + _fname,
FormsAuthentication.FormsCookiePath);
string hashed_ticket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashed_ticket);
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
Response.Cookies.Add(cookie);
Response.Redirect("UserProfile.aspx");
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
}
}
Master page HTML:
<ul class="nav navbar-nav navbar-right">
<li><asp:LinkButton ID="login" runat="server"
PostBackUrl="~/Login1.aspx">Login</asp:LinkButton> </li>
<li> <asp:LinkButton ID="Logout" runat="server" CausesValidation="False" onclick="Logout_Click" style="text-align: right">(logout)</asp:LinkButton></li>
</ul>
Code behind Master Page:
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
Logout.Visible = false;
}
else
{
Logout.Visible = true;
if (Request.Cookies[FormsAuthentication.FormsCookiePath] != null)
{
FormsIdentity user = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = user.Ticket;
login.Text = "You are logged-in " + ticket.UserData.Split('.')+ "!";
}
}
Best Answer