How to intercept an authentication request in ASP.net webform - asp.net

I have user's who are losing their data because they sit on a page too long, then are asked to log back in. I want to do the following:
1) Instead of redirecting them to a login page, I want to cancel the current request and give the user a popup dialog box to login with.
2) When the login is successful, I want the user to be sent back to their form, with all data intact. (Even better if the request could go through without sending them back to that form, but this is optional).
How can I intercept these authentication requests, and present the user with a popup login?
I am using ASP.net forms authentication.

You can intercept this event on Application_AuthenticateRequest in Global.asax
But, you need be more specific, are you using the ASP.NET Forms Authentication?
Added:
Try this and reply me
In Global.asax
void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (HttpContext.Current.User == null)
{
FormsAuthenticationTicket ticket = new
FormsAuthenticationTicket(1, "Anonymous", DateTime.Now, DateTime.Now.AddMinutes(30), false, "Anonymous");
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie =
new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(cookie);
FormsIdentity id = new FormsIdentity(ticket);
System.Security.Principal.GenericPrincipal principal = new System.Security.Principal.GenericPrincipal(id, ticket.UserData.Split(new char[] { '|' }));
Context.User = principal;
}
}
In a web form
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket.UserData == "Anonymous")
{
//Throw the login popup
}
else
{
//Some Code
}

Are you using a master page? You could redirect to there when login is required, not a separate login page. In the login code in the master page you then decided whether to redirect to a proper, standalone login page, or make a login div visible as a popup.

Related

Cookies in ASP.NET-Call Back to another page

do you know how cookies works on ASP.NET? could you tell me?
and how to call the cookies to another page?
i have login form, and i use cookies. but i can't call that cookies to another page. i want to use some data from login form (it's like domain name, username and password) to do change password from changepassword.aspx form.
somebody please help me.
void Login_Click(object sender, EventArgs e)
{
string adPath = "LDAP://mydomain.com"; //Path to your LDAP directory server
LdapAuthentication adAuth = new LdapAuthentication(adPath);
try
{
if(true == adAuth.IsAuthenticated(txtDomain.Text, txtUsername.Text, txtPassword.Text))
{
//string groups = adAuth.GetGroups();
string groups = txtUsername.Text;
//Create the ticket, and add the groups.
bool isCookiePersistent = chkPersist.Checked;
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
txtUsername.Text,DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, groups);
//Encrypt the ticket.
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
//Create a cookie, and then add the encrypted ticket to the cookie as data.
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
if(true == isCookiePersistent)
authCookie.Expires = authTicket.Expiration;
//Add the cookie to the outgoing cookies collection.
Response.Cookies.Add(authCookie);
//You can redirect now.
Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, false));
}
else
{
errorLabel.Text = "Authentication did not succeed. Check user name and password.";
}
}
catch(Exception ex)
{
errorLabel.Text = "Error authenticating. " + ex.Message;
}
}
</script>
this is how use cookies in login form.
how can i use cookies in change password form?

GenericPrincipal IsInRole returns false for HttpContext.User

I have a credential method to set user credentials via GenericPrincipal. I am using asp.net MVC
public void SetCredentials(HttpContextBase context, string username, bool createPersistenceCookie)
{
FormsAuthentication.SetAuthCookie(username, createPersistenceCookie);
IIdentity identity = new GenericIdentity(username);
IPrincipal principal = new GenericPrincipal(identity,new []{"standart"});
context.User = principal;
}
I want to check User.IsInRole("standart") in controller action, but it returns false.
context.User.IsInRole("standart") //returns false
I want to use context.User in my application, but it returns always false.
I think you used asp.net membership api before. And now you want to create custom principal in your application.
When you send request to server, server uses a new clean HttpContext. So you lost your old informations. If you want to use old session informations is application, you shuld save your data in server or client side. You can do this two way.
Client cookie
Server session
I recommand you to use client cookies. Because data is being stored to client side, so you save server resources.
public void SetCredentials(HttpContextBase context, string username, bool createPersistenceCookie)
{
var formsAuthenticationTicket = new FormsAuthenticationTicket(
1,
username,
DateTime.Now,
DateTime.Now.AddMilliseconds(FormsAuthentication.Timeout.TotalMilliseconds),
createPersistenceCookie,
roles
);
var encryptedTicket = FormsAuthentication.Encrypt(formsAuthenticationTicket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
HttpContext.Current.Response.AppendCookie(authCookie);
}
I sended encrypted cookie to client side. And I should check this cookie all incoming request to server application.
And now in Global.asax file:
protected void Application_AuthenticateRequest(object sender, System.EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null) return;
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
IIdentity identity = new GenericIdentity(ticket.Name);
IPrincipal principal = new GenericPrincipal(identity, ticket.UserData.Split('|'));
HttpContext.Current.User = principal;
}
I hope solve your issue.

Authenticating user with second login

asp.net I am using a second login control to verify a users email. They will get an Email that directs them to a confirm login window. Not the login that is used in the web.config file. So. I assumed that when they entered the loggedin event the would be authenticated, but it seems they are not. All I want to do here is set the profile property 'confirmed' = Y. So I added code:
protected void Login1_LoggedIn(object sender, EventArgs e)
{
TextBox userName = (TextBox)Login1.FindControl("UserName");
string uname = userName.Text;
TextBox Password = (TextBox)Login1.FindControl("Password");
if (Membership.ValidateUser(userName.Text, Password.Text) == true)
{
BDrider bd = new BDrider();
string UserData = bd.getRidFromUsername(uname).ToString();
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, uname, DateTime.Now, DateTime.Now.AddMonths(3), false, UserData, FormsAuthentication.FormsCookiePath);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(authCookie);
if (User.Identity.IsAuthenticated)
{
Profile.confirmed = "Y";
}
Response.Redirect("~/Main/Main.aspx");
}
}
But on the IsAuthenticated line it returns false ???
Seems that you are creating the cookie and trying to "consume it" in the very same request. Unfortunately, this won't work. The forms authentication module will pick up the cookie and maintain the session starting from just the next request.
A possible workaround would be to redirect to an auxiliary page and perform your operation there and then redirect to Main.aspx. Your code would be then
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, uname, DateTime.Now, DateTime.Now.AddMonths(3), false, UserData, FormsAuthentication.FormsCookiePath);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(authCookie);
Response.Redirect( "Auxiliary.aspx" );
and in the Auxiliary.aspx:
if (User.Identity.IsAuthenticated)
{
Profile.confirmed = "Y";
}
Response.Redirect("~/Main/Main.aspx");
However, I don't quite get the if. If you are just issuing the forms cookie, the user surely is authenticated. Why it would be otherwise?

Log out asp.net incomplete

I'm having this annoying problem that when i log out from asp mvc web application it's not working to
logging again.
Log out method looks like:
private static void LogOut()
{
FormsAuthentication.SignOut();
Session.Clear();
Session.Abandon();
Response.Cookies.Clear();
Response.Redirect("~/Login.aspx");
}
is that cookies does not allow to login again?
You set the cookie expiry date to past to make the cookie invalid.
FormsAuthentication.SignOut();
Session.Abandon();
// clear authentication cookie using expiration date
HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
cookie1.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie1);
// clear session cookie, if needed
HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
cookie2.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie2);
FormsAuthentication.RedirectToLoginPage();
Forms Authentication Methods

Asp.net form login Impossible when client date time differ from server

FormsAuthenticationUserData userData = new FormsAuthenticationUserData(member.Id, member.Role, member.Gender);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, member.UserName, DateTime.Now, DateTime.Now.AddHours(24), true, userData.Serialize());
string encTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
faCookie.Expires = DateTime.Now.AddHours(25);
Response.Cookies.Add(faCookie);
string redirectUrl = FormsAuthentication.GetRedirectUrl(member.UserName, false);
Response.Redirect(redirectUrl, true);
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
try
{
WebIdentity identity = new WebIdentity(authTicket.Name, authTicket.UserData);
WebPrincipal currentMember = new WebPrincipal(identity);
Context.User = currentMember;
}
catch
{
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
Response.End();
}
}
}
the user cannot login when client date time is greater than server date time (make cookie null and cannot login)
what is solution?
thanx a lot!
After reading your comment, this is expected behaviour that cannot be changed. The system is doing what it is meant to. You could set the cookie expire later or use a rolling timeout, however, I see no reason for the machine datetime to be out by so far.
This technique avoids using the browser's date/time completely.
Set the FormsAuthentication cookie to never expire, or to expire after 100 years.
Store the actual expiration based on server time in the authenticationTicket.Expiration property. See here.
After the server authenticates a request, it should check the authenticationTicket.Expiration to see if it has expired. I'm not 100% sure the system does this automatically, you may have to hook into the Application_AuthenticateRequest event and do it yourself.
If it has expired, the web server should deny the request; render an HTTP 403 status code and a set-cookie header to remove the cookie at that point.

Resources