ASP.NET Forms Authentication with Windows Safari - asp.net

Does anyone know why ASP.NET Forms Authentication does not work on windows safari, or better yet, how to get it to work? It seems like a very weird issue. When I use a login control (System.Web.UI.WebControls.Login) everything works fine, but if I try to do a custom Forms Authentication login when I call FormsAuthentication.RedirectFromLoginPage safari just sends me back to the login page as if I'm not authenticated whereas every other browser logs me in and sends me on my way.
protected void lnkLogin_Click(object sender, EventArgs e)
{
if (Membership.Provider.ValidateUser(txtUsername.Text, txtPassword.Text))
{
Session.Clear();
HttpContext.Current.Response.Cookies.Clear();
FormsAuthentication.SetAuthCookie(txtUsername.Text, true);
FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);
}
}

Try either SetAuthCookie, or RedirectFromLoginPage. The redirect needs to know where to redirect to anyway (ReturnUrl), maybe that is your problem.
if (Request.QueryString["ReturnUrl"] != null)
{
FormsAuthentication.RedirectFromLoginPage("someuserid", false);
}
else
{
FormsAuthentication.SetAuthCookie("someuserid", false);
Response.Redirect("~/SomePage.aspx");
}

This works fine for me in Safari:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
//check login
User user = UserBAL.GetUser(Login1.UserName, Login1.Password);
//null and filled object check
if (user != null && user.Id > 0 && user.Roles != null && user.Roles.Count > 0)
{
e.Authenticated = true;
FormsAuthenticationTicket authTicket = new
FormsAuthenticationTicket(1, //version
Login1.UserName, // user name
DateTime.Now, // creation
DateTime.Now.AddMinutes(60),// Expiration
false, // Persistent
string.Join("|", user.Roles.ToArray())); // User ata
// Now encrypt the ticket.
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
// Create a cookie and add the encrypted ticket to the
// cookie as data.
HttpCookie authCookie =
new HttpCookie(FormsAuthentication.FormsCookieName,
encryptedTicket);
Response.Cookies.Add(authCookie);
//redirect
Response.Redirect(FormsAuthentication.GetRedirectUrl(
Login1.UserName,
false));
}
else
{
Login1.FailureText = "Login failed.";
}
}

Related

When ReturnUrl loads last page after Login.It should load with all last values that i was working on?

I'm Using a returnurl cookie to store current Url when Login cookie expires,And when User Again login,It redirect user to last page he was working on.But all his work gone,all data gone.Is it possible when user comeback after login he get all his text-box data what he filled?
I have seen this Happening in Shopping Site where user can add-to-cart fill all details but can't Check out if not login,when he do login he get all his data back as he left .
Note:I don't want to use Session to store each and every data of page and fetch values when page reloads
I'm not Using windows form Authentication for login. I'm generating my own cookie
Here's Code:In master Page Userinfo() Checks cookies exist or not . And Linkbutton is logout Button
public void UserInfo()
{
HttpCookie LoginCredentialscookie = Request.Cookies["LoginCredentials"];
if (Request.Cookies["LoginCredentials"] != null && LoginCredentialscookie != null && LoginCredentialscookie.Values != null && LoginCredentialscookie.Values["LoginID"] != null && LoginCredentialscookie.Values["Name"] != null)
{
lblUserName.Text = Request.Cookies["LoginCredentials"].Values["Name"].ToString();
}
else
{
Response.Cookies.Add(new HttpCookie("returnUrl", Request.Url.PathAndQuery));
Response.Redirect("login.aspx");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
HttpCookie acookie = new HttpCookie("LoginCredentials");
acookie.Expires = DateTime.Now.AddHours(-1);
Response.SetCookie(acookie);
Response.Redirect("Eminent.aspx");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();
}
Here is Code in login.aspx
HttpCookie returnCookie = Request.Cookies["returnUrl"];
if ((returnCookie == null) || string.IsNullOrEmpty(returnCookie.Value))
{
Response.Redirect("Home.aspx");
}
else
{
HttpCookie deleteCookie = new HttpCookie("returnUrl");
deleteCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(deleteCookie);
Response.Redirect(returnCookie.Value);
}
I've done this recently, albeit using MVC.
The page saved the Object/Model in session, this was persisted into the database as serialized/deserialized XML.
Once the user logs back in, I set the session from the value saved into the database.
Further reading
http://www.codeproject.com/Articles/36781/Serialization-and-Deserialization-in-ASP-NET-with

How to implement keep me logged in asp.net

How to implement keep me logged in asp.net using login control and membership in asp.net
By adding a checkbox..
And if it's checked you have to create a cookie with authentication and if it's not checked you have to put it in session
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.aspx
Another way is to implement a cookie that's not persistent if it's unchecked like that:
int timeout = rememberMe ? 525600 : 30; // Timeout in minutes, 525600 = 365 days.
var ticket = new FormsAuthenticationTicket(userName, rememberMe, timeout);
string encrypted = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Expires = System.DateTime.Now.AddMinutes(timeout);
cookie.HttpOnly = true; // cookie not available in javascript.
Response.Cookies.Add(cookie);
First you need to create Cookie on login button click as follows and Store the Login Detail in it
protected void btnLogin_Click(object sender, System.EventArgs e)
{
string username = txtUsername.Text;
string Password = txtPassword.Text;
// Create Cookie and Store the Login Detail in it if check box is checked
if ((CheckBox1.Checked == true)) {
HttpCookie mycookie = new HttpCookie("LoginDetail");
mycookie.Values("Username") = txtUsername.Text.Trim();
mycookie.Values("Password") = txtPassword.Text.Trim();
mycookie.Expires = System.DateTime.Now.AddDays(1);
Response.Cookies.Add(mycookie);
}
Response.Redirect("Default2.aspx");
}
then check if cookie exists (is remember me checked), if yes fill the details as follows-
protected void Page_Load(object sender, System.EventArgs e)
{
//check if cookie exist then login page from
if ((Response.Cookies("LoginDetail") != null)) {
//Username
string uname = Response.Cookies("LoginDetail").Values("Username").ToString();
string pass = Response.Cookies("LoginDetail").Values("Username").ToString();
Response.Redirect("Default2.aspx");
}
}

Accessing Sessions Variables in code behind

Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Session["Authenticated"] )
{
Response.Redirect( "index.aspx", false );
}
}
Once they login I set the session to true. Basically, if they don't have an active session I want them re-directed back to the index/login page. How do I accomplish this?
Use this check
if(Session["Authenticated"] == null || !(bool)Session["Authenticated"])
If you are using cookie, you can store a marker in your cookie so you can tell the difference between "fresh browser + new session" and "old browser + expired session".
Below is sample code that will redirect the user to an expired page if the session has expired.
void Session_OnStart(Object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
HttpCookieCollection cookies = context.Request.Cookies;
if (cookies["starttime"] == null) {
HttpCookie cookie = new HttpCookie("starttime", DateTime.Now.ToString());
cookie.Path = "/";
context.Response.Cookies.Add(cookie);
}
else {
context.Response.Redirect("expired.aspx");
}
}
And if you are trying to implement sessions this might help you http://aspalliance.com/1621_Implementing_a_Session_Timeout_Page_in_ASPNET.2

How to properly authenticate mvc-mini-profiler with AspNetSqlMembershipProvider

I tried to check if the user is in role at Application_BeginRequest and Application_AuthenticateRequest with this code and it will not work. At BeginRequest the code is never hit and Authenticate it's hit with some of the request and the profiler does not show up.
Checking only for Request.IsLocal works fine.
if(Request.IsAuthenticated)
{
if(User.IsInRole("Admin");
MiniProfiler.Start();
}
Any idea or why it's not working or better way to do it?
[Update] I accepted the awnser but undid it as I didn't quite get it do work
I did the following but the profiler is not showing up at first.
After a few tries it started showing up, even when I tried to acess the site with incognito mode, so no cookie.
protected void Application_PostAuthorizeRequest(Object sender, EventArgs e)
{
if (User.IsInRole("Admin"))
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("RoleProfiler");
if (cookie == null)
{
cookie = new HttpCookie("RoleProfiler");
cookie.Value = "yes";
cookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(cookie);
}
}
}
And I'm checking with
protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("RoleProfiler");
if ((cookie != null) && (cookie.Value == "yes") )
{
MvcMiniProfiler.MiniProfiler.Start();
}
}
And ending at the end of the request.
protected void Application_EndRequest()
{
MvcMiniProfiler.MiniProfiler.Stop();
}
[Update2] Closing question, ignore this, I was being owned by outputcache.
The cookie feanz mentions is a handy trick, a second method is profiling unconditionally and then abandoning the session for an unauthenticated user:
protected void Application_BeginRequest()
{
MvcMiniProfiler.MiniProfiler.Start();
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if(!CurrentUserIsAllowedToSeeProfiler())
{
MvcMiniProfiler.MiniProfiler.Stop(discardResults: true);
}
}
Begin request happens before the user is fully authenticated in the request life cycle.
I solved this issue by adding a cookie if the user is in a role ("Admin" in your case) when the request is authenticated then you can check for this cookie on begin request and initialise the profiler.
It wont't work the first time but should every time after that.
This is my 2cent.
context.AcquireRequestState += (sender, e) =>
{
// Check debug in session. Can be set from Querystring. (?debug=true)
if (HttpContext.Current.Session != null && HttpContext.Current.Session["Debug"] != null)
{
try{
bool debug = (bool)HttpContext.Current.Session["Debug"];
if (debug == true)
MiniProfiler.Start();
else
MiniProfiler.Stop(discardResults: true);
}
catch{
MiniProfiler.Stop(discardResults: true);
}
}// Or always show if Administrator.
else if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
{
bool admin = HttpContext.Current.User.IsInRole("Administrator");
if (admin == false)
{
MiniProfiler.Stop(discardResults: true);
}
}
else
{
MiniProfiler.Stop(discardResults: true);
}
};

Login control - error

There is a Login control on my ASP.NET (2.0) page. I handle LoggingIn event like this:
protected void Login1_LoggingIn(object sender, LoginCancelEventArgs e)
{
// go to database and find this user
if (userTable != null && userTable.Rows.Count > 0)
{
int userID = Convert.ToInt32(userTable.Rows[0]["UserID"]);
HttpCookie userIdCookie = new HttpCookie("UserID", userID.ToString());
Response.AppendCookie(userIdCookie);
}
else
{
e.Cancel = true;
}
}
User found in database. And at the end of this function e.Cancel still set to false. But then occured LoginError. LoggedIn doesn't occured. And FailureText appears on the page. I don't know how to debug this :(
Have you also handled the Authenticate event?
<asp:Login id="Login1" runat="server"
OnAuthenticate="MyOnAuthenticate">
private void MyOnAuthenticate(object sender, AuthenticateEventArgs e)
{
bool isAuthenticated = false;
isAuthenticated = YourAuthenticationMethod(Login1.UserName, Login1.Password);
e.Authenticated = isAuthenticated;
}
private bool YourAuthenticationMethod(string UserName, string pwd)
{
// Insert code that implements a site-specific custom
// authentication method here.
}
LoginControl's Authenticated event on MSDN

Resources