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?
Related
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?
In the debugger, if I dig into the User object, I can see the current member's UserData property, ((System.Web.Security.FormsIdentity(User.Identity)).Ticket.UserData, has "admin" in it.
User.Identity.IsAuthenticated works but User.IsInRole("admin") returns false.
If "admin" is in the UserData property, then why doesn't User.IsInRole("admin") return true?
In my login method I have the authentication ticket set up as follows:
FormsAuthenticationTicket _ticket = new FormsAuthenticationTicket(1, lUserName.Text, DateTime.Now, DateTime.Now.AddMonths(1), chk_remember.Checked, Role, FormsAuthentication.FormsCookiePath);
string encTicket = FormsAuthentication.Encrypt(_ticket);
HttpCookie _cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
if (chk_remember.Checked)
_cookie.Expires = DateTime.Now.AddMonths(1);
Response.Cookies.Add(_cookie);
you need to put this code in your Global.asax
protected void Application_AuthenticateRequest(Object sender,
EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id =
(FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
// Get the stored user-data, in this case, our roles
string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new GenericPrincipal(id, roles);
}
}
}
}
for more information you can see this link form authentication
Here my cookie create code:
This is controller (model.RememberMe is a checkbox value)
int timeout = (model.RememberMe) ? (int) FormsAuthentication.Timeout.TotalMinutes : Session.Timeout;//4h
HttpCookie cookie = accountService.GetCookie(userId, model.RememberMe, timeout);
Response.Cookies.Add(cookie);
Logger.Debug("POST: AccountController LogOn end.");
result = returnUrl != null
? RedirectToLocal(returnUrl)
: RedirectToAction("Index", "Profile", new {id = userId});
Service method that's create cookie
public HttpCookie GetCookie(int userId, bool rememberMe, int timeout)
{
Logger.Trace("AccountService GetCookie start with arguments:" +
" userId = {0}, rememberMe = {1}.", userId, rememberMe);
var authTicket = new FormsAuthenticationTicket(
1,
Convert.ToString(userId),
DateTime.Now,
DateTime.Now.AddMinutes(timeout),
rememberMe,
string.Empty,
"/"
);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(authTicket));
Logger.Debug("Cookie for user with userId = {0} has created", userId);
Logger.Trace("AccountService GetCookie end.");
return cookie;
}
But unfortunately RememberMe dont work and cookies expires at the end of the browser session.Why?
What is the purpose of FormsAuthenticationTicket isPersistent property? Here some kind of answer but i dont understand why it doesnt work?
The difference between your code and the SO answer that you linked is that they use:
FormsAuthentication.SetAuthCookie(model.UserName, true);
Which makes the cookie with proper expiration time based on the IsPersistent property. However, if you return the cookie with the constructor like in your code:
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(authTicket));
Then the expiration time will be set to browser-session because that is the default behavior of the HttpCookie class: what is the default expiration time of a cookie
So you probably have two options. Use the FormsAuthentication.SetAuthCookie method outlined in the answer you linked to, or add:
cookie.Expires = DateTime.Now.AddMinutes(10); // or whatever you want
I have the following code to add authentication cookie to the response and redirect to homepage
HttpCookie authCookie = FormsAuthentication.GetAuthCookie(username, true);
Response.Cookies.Add(authCookie);
Response.Redirect("~/Home/Home.aspx");
But in the Home.aspx, User.Identity.IsAuthenticated is still false. why?
Finally got it working. Here is it in nutshell
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
username,
DateTime.Now,
DateTime.Now.AddMinutes(30),
isPersistent,
userData,
FormsAuthentication.FormsCookiePath);
// Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(ticket);
// Create the cookie.
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
I followed the code sample from this MSDN page:
You don't have to add the cookie to the response yourself.
You were doing this:
HttpCookie authCookie = FormsAuthentication.GetAuthCookie(username, true);
Response.Cookies.Add(authCookie);
Response.Redirect("~/Home/Home.aspx");
But instead of doing a GetAuthCookie and then adding it, you can just use SetAuthCookie:
HttpCookie authCookie = FormsAuthentication.SetAuthCookie(username, true);
Response.Redirect("~/Home/Home.aspx");
When you look at the MSDN page for SetAuthCookie, you see that it not only adds the cookie to the Response (or the URL), but it also creates and encrypts a ticket:
Creates an authentication ticket for the supplied user name and adds it to the cookies collection of the response, or to the URL if you are using cookieless authentication.
That's probably why it doesn't work when you just try to add the cookie yourself.
OK, here's my code to create an authentication cookie:
// get user's role
List<UserType> roles = rc.rolesRepository.GetUserRoles(rc.userLoginRepository.GetUserID(userName));
List<string> rolesList = (from r in roles
select r.ToString()).ToList();
string[] rolesArr = rolesList.ToArray();
// create encryption cookie
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
userName,
DateTime.Now,
DateTime.Now.AddDays(90),
createPersistentCookie,
String.Join(";",rolesArr) //user's roles
);
// add cookie to response stream
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
//FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
And here's my code in Global.asax to set the user roles into the user identity:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null || authCookie.Value == "")
{
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
string[] roles = authTicket.UserData.Split(new char[] { ';' });
if (Context.User != null)
{
Context.User = new System.Security.Principal.GenericPrincipal(Context.User.Identity, roles);
}
}
catch
{
return;
}
}
However, if "createPersistentCookie" is TRUE in the top example, no persistent cookie is created. If I uncomment the last line like so:
//System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
then the persistent cookie is created on my hard drive. BUT then in the Global.asax code, the UserData field in "authTicket" is blank, so I can't set up the roles properly!
So I have to use SetAuthCookie to create a persistent cookie, but then for some reason the UserData field disappears from the persistent cookie.
What is the answer to this??
To create a persistent cookie you need to set the Expires property:
if (authTicket.IsPersistent)
{
authCookie.Expires = authTicket.Expiration;
}