Hi
In Authenticate User it is going in else part.
C#
Login Page
using (SqlConnection con = new SqlConnection(Common.CommonFunction.cnn_Live))
{
string UserId = txtUserId.Text;
string Pwd = Common.CommonFunction.EncodePasswordToBase64(txtPassword.Text.ToUpper());
SqlCommand cmd = new SqlCommand("sp_Login", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@UserId", UserId);
cmd.Parameters.AddWithValue("@Password", Pwd);
SqlParameter successParam = cmd.Parameters.Add("@Success", SqlDbType.Bit);
successParam.Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
bool success = (bool)successParam.Value;
if (success)
{
Response.Redirect("~/Admin/Department.aspx");
}
else
{
//ShowMessage("Oops...", success.ToString(), "error");
}
}
Department Page
if (!Page.IsPostBack)
{
var authenticatedUser = Common.CommonFunction.AuthenticatedUser();
if (authenticatedUser.Item1) // Check if the user is authenticated
{
var userRole = authenticatedUser.Item2;
var loginId = authenticatedUser.Item3;
}
else
{
// Handle unauthenticated scenario if needed
}
}
public static Tuple AuthenticatedUser()
{
try
{
if (HtpContext.Current.User.Identity.IsAuthenticated) //Check if user is loged in or not
{
FormsIdentity id = (FormsIdentity)HtpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
return Tuple.Create(true, ticket.UserData, Convert.ToString(HtpContext.Current.User.Identity.Name));
}
else
{
FormsAuthentication.RedirectToLoginPage();
return Tuple.Create(false, "", "");
}
}
catch (Exception ex)
{
FormsAuthentication.RedirectToLoginPage();
return Tuple.Create(false, "", "");
}
}Thanks

Aman GuptaRank #193 · 12.4K reputationPosted Aug 20, 2024, 2:34 AM EDT
Hi Ramco,
The issue seems to be related to user authentication not working as expected, causing the application to fall into the "else" part of the logic in the
AuthenticatedUsermethod.Step 1: Ensure Proper Setting of the Authentication Ticket
After successfully validating the user's credentials in the login page, you need to create and set a FormsAuthenticationTicket. This will ensure that the user is authenticated across different pages.
Login Page Code Update:
using (SqlConnection con = new SqlConnection(Common.CommonFunction.cnn_Live)) { string UserId = txtUserId.Text; string Pwd = Common.CommonFunction.EncodePasswordToBase64(txtPassword.Text.ToUpper()); SqlCommand cmd = new SqlCommand("sp_Login", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@UserId", UserId); cmd.Parameters.AddWithValue("@Password", Pwd); SqlParameter successParam = cmd.Parameters.Add("@Success", SqlDbType.Bit); successParam.Direction = ParameterDirection.Output; con.Open(); cmd.ExecuteNonQuery(); bool success = (bool)successParam.Value; if (success) { // Create the authentication ticket FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, // Ticket version UserId, // Username associated with the ticket DateTime.Now, // Date/time issued DateTime.Now.AddMinutes(30), // Date/time to expire false, // Persistent user cookie "UserRole", // User data (e.g., role, other info) FormsAuthentication.FormsCookiePath); // Cookie path // Encrypt the ticket string encryptedTicket = FormsAuthentication.Encrypt(ticket); // Create and add the authentication cookie HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); HttpContext.Current.Response.Cookies.Add(authCookie); // Redirect to the requested page Response.Redirect("~/Admin/Department.aspx"); } else { // Optionally, show a message to the user // ShowMessage("Invalid username or password.", "Error", "error"); } }Step 2: Correct the Typo in AuthenticatedUser Method
Ensure that the class name is correctly referenced as HttpContext, not HtpContext.
AuthenticatedUser Method Update:
public static Tuple AuthenticatedUser() { try { if (HttpContext.Current.User.Identity.IsAuthenticated) // Check if user is logged in or not { FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity; FormsAuthenticationTicket ticket = id.Ticket; return Tuple.Create(true, ticket.UserData, Convert.ToString(HttpContext.Current.User.Identity.Name)); } else { FormsAuthentication.RedirectToLoginPage(); return Tuple.Create(false, "", ""); } } catch (Exception ex) { FormsAuthentication.RedirectToLoginPage(); return Tuple.Create(false, "", ""); } }Step 3: Verify web.config Settings
Ensure that your web.config is properly configured for Forms Authentication.
web.config Update (if needed):
Step 4: Test the Solution
Debug the Login Page: Ensure that the FormsAuthenticationTicket is being created and added to the response correctly.
Check the Department Page: After logging in, navigate to the Department.aspx page and ensure that the AuthenticatedUser method correctly identifies the user as authenticated.
This should resolve the issue where the code was falling into the "else" part, and the user was not being recognized as authenticated.
Ramco RamcoRank #462 · 5.4K reputationPosted Aug 20, 2024, 2:37 AM EDT
Hi Aman
How the below code works. Secondly what does timeout(30) means
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, // Ticket version UserId, // Username associated with the ticket DateTime.Now, // Date/time issued DateTime.Now.AddMinutes(30), // Date/time to expire false, // Persistent user cookie "UserRole", // User data (e.g., role, other info) FormsAuthentication.FormsCookiePath); // Cookie path // Encrypt the ticket string encryptedTicket = FormsAuthentication.Encrypt(ticket); // Create and add the authentication cookie HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); HttpContext.Current.Response.Cookies.Add(authCookie);Thanks
Aman GuptaRank #193 · 12.4K reputationPosted Aug 22, 2024, 1:49 AM EDT
Hi Ramco,
Sorry for Delayed Response.
How the Code Works:
FormsAuthenticationTicket Creation:
The code creates a new FormsAuthenticationTicket object, which represents the authentication ticket used to identify an authenticated user.
Parameters:
Version (1): Specifies the version of the ticket.
UserId (UserId): The username or ID associated with the ticket.
Issue Date (DateTime.Now): The date and time when the ticket is issued.
Expiration Date (DateTime.Now.AddMinutes(30)): Specifies when the ticket will expire, in this case, 30 minutes after it is issued.
IsPersistent (false): Indicates whether the authentication ticket will persist between browser sessions (false means it will not be stored in a persistent cookie).
UserData ("UserRole"): Custom data you can store with the ticket, often used to store user roles or other info.
Cookie Path (FormsAuthentication.FormsCookiePath): Defines the path for the authentication cookie.
Encrypting the Ticket:
The FormsAuthentication.Encrypt method is used to encrypt the ticket into a string that can be safely stored in a cookie.
Creating the Authentication Cookie:
A new HttpCookie object is created using the encrypted ticket string. This cookie will be sent to the client and used to authenticate the user on subsequent requests.
Adding the Cookie to the Response:
The cookie is added to the HTTP response, which sends it to the client's browser.
What timeout(30) Means:
timeout(30) is not directly related to the provided code, but if you meant DateTime.Now.AddMinutes(30), it specifies the expiration time for the authentication ticket. The ticket will expire 30 minutes after it is issued.
If timeout(30) was mentioned elsewhere, please clarify the context so I can provide a more accurate explanation.