Hi
In Authenticate User it is going in else part.
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 GuptaPosted Aug 22, 2024, 5:49 AM
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.
Ramco RamcoPosted Aug 20, 2024, 6:37 AM
Hi Aman
How the below code works. Secondly what does timeout(30) means
Thanks
Aman GuptaPosted Aug 20, 2024, 6:34 AM
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:
Step 2: Correct the Typo in AuthenticatedUser Method
Ensure that the class name is correctly referenced as HttpContext, not HtpContext.
AuthenticatedUser Method Update:
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.