So I have a login page where I set my own cookie and FormsAuthenticationTicket. However, when I finally choose to redirect the user to the new homepage after logging in, it refuses. It just redirects right back to the login page for no reason. I don’t understand why.
My web.config with part of the machinekey removed:
<authentication mode="Forms">
<forms loginUrl="~/Login.aspx" defaultUrl="~/Default.aspx" cookieless="UseCookies" name=".ASPXFORMSAUTH" timeout="50" />
</authentication>
<authorization>
<allow users="*" />
</authorization>
<machineKey decryption="AES" validation="SHA1" ........ />
My Login click event after entering username/pass and authenticating it as true:
if (Authenticated)
{
//Create Form Authentication ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(30), false, userName, FormsAuthentication.FormsCookiePath);
string encryptedCookie = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedCookie);
Response.Cookies.Add(cookie);
Response.Redirect("MainPage.aspx", true);
}
MasterPage checks to make sure only certain pages can be accessed:
else if (Context.User.Identity.IsAuthenticated)
{
if (Session["uid"] == null)
{
userclass u = new userclass();
int uid = -1;
uid = (int)u.Getuseridbyusername(Context.User.Identity.Name);
if (uid != -1)
{
Session["uid"] = uid;
}
}
} else if (!Context.User.Identity.IsAuthenticated)
{
// First check if user is was redirected to ChangePassword
if (!Request.Path.Contains("ForgotPass.aspx") && !Request.Path.Contains("ChangePass.aspx") && !Request.Path.Contains("CreateAccount.aspx") && !Request.Path.Contains("Error.aspx") && !Request.Path.Contains("Logout"))
{
if (!Request.Path.Contains("Login"))
FormsAuthentication.RedirectToLoginPage();
}
}
Commenting out RedirectToLoginPage() has no effect. Trying to use RedirectFromLoginPage has no effect. Trying to use <allow users=”?” /> has no effect. Trying to use <deny users=”?” /> in conjunction has no effect.
EDIT: Cookie is set according to browser traffic. But no redirect is coming through. Apparently, either you cannot redirect after setting a cookie or ASP.NET doesn’t know how to read instructions.
Solved. Apparently, I did have a Redirect somewhere that was taking the user back to the login page even though the cookie is set and Context.User.Identity.IsAuthenticated was returning true because the session variable “uid” was being set.