ASP.NET MVC Adding Cookies doesn't work if Domain Set - asp.net

I am trying to add two cookies to application. One I need the domain to ".site.com", but that one does not show in the Cookies.
var ticket = new FormsAuthenticationTicket(1, emailAddress, DateTime.Now.AddHours(-1), DateTime.Now.AddMonths(12), true, accessToken);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
{
HttpOnly = true,
Expires = DateTime.Now.AddMonths(12)
};
var subDomainCookie = new HttpCookie("site.session.token", accessToken)
{
HttpOnly = false,
Expires = DateTime.Now.AddMonths(12),
Domain = ".site.com",
Path = "/",
Shareable = true
};
Response.Cookies.Add(cookie);
Response.Cookies.Add(subDomainCookie);
What am I missing?

Related

remember me(isPersistent) dont work on Forms 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

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?

aspnet auth cookie twice in Request

I'm dealing with custom authentication cookie in AspNet web app.
Using asp:Login component, here is how user is authenticated:
void L_Authenticate(object sender, AuthenticateEventArgs e)
{
if (L.UserName == "john" && L.Password == "cookie")
{
FormsAuthenticationTicket ticket =
new FormsAuthenticationTicket(1, "john",
DateTime.Now,
DateTime.Now.AddSeconds(30),
false, "");
var cookieConnexion = new HttpCookie("myCookie");
cookieConnexion.Value = FormsAuthentication.Encrypt(ticket);
cookieConnexion.Expires = ticket.Expiration;
this.Response.Cookies.Set(cookieConnexion);
Z.Text = "<a href='/Prive/Home.aspx'>next</a>";
}
}
First of all, I don't set e.Authenticated = true or .ASPXAUTH cookie will be created. I don't want that. Second, I don't do Response.Redirect.
Now, in Global.asax, User is set in current HttpContext:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
{
}
else
{
var cookie = this.Request.Cookies["myCookie"];
if (cookie != null)
{
var ticket = FormsAuthentication.Decrypt(cookie.Value);
if (ticket != null)
{
HttpContext.Current.User =
new ClientRolePrincipal(new GenericIdentity(ticket.Name));
ticket = new FormsAuthenticationTicket(1, ticket.Name,
DateTime.Now,
DateTime.Now.AddSeconds(30),
false, ticket.UserData);
cookie.Value = FormsAuthentication.Encrypt(ticket);
cookie.Expires = ticket.Expiration;
this.Response.Cookies.Set(cookie);
}
}
}
}
First request to the app (using chrome dev tools, I track down cookies in request/responses headers):
0 cookie in request
0 cookie in response: ASP.NET_SessionId
User logs in:
1 cookie in request: ASP.NET_SessionId
1 cookie in response: myCookie
User browses to Home.aspx:
2 cookies in request: ASP.NET_SessionId, myCookie
1 cookie in response: myCookie (renewed)
OK.
Now, if on PreRender I display elements contained in this.Request.Cookies, I see twice myCookie. Why?
ASP.NET_SessionId, domain '' , path '/', value = nk1cy255quh32o45hxtg4x55
myCookie, domain '' , path '/', value = BF6246B7E5A5100AA59A7B7237B446...
myCookie, domain '' , path '/', value = BF6246B7E5A5100AA59A7B7237B446...

Cookie is the same from two different browser machine clients

I have two browsers from two different machines hitting a test page. The test page is retrieving a cookie. If one is not there, it creates a cookie.
public string GetUserCookieId()
{
string cookieName = "CookieId3";
HttpCookie userInfoCookies = Request.Cookies[cookieName];
string cookieId = "";
if (userInfoCookies != null)
cookieId = userInfoCookies.Value;
if (string.IsNullOrEmpty(cookieId))
{
cookieId = Guid.NewGuid().ToString();
HttpCookie cookie = new HttpCookie(cookieName);
cookie.Value = cookieId;
cookie.Expires = DateTime.Now.AddDays(90);
Response.SetCookie(cookie);
}
return cookieId;
}
Both browser machines are displaying the same cookie value on the page. This even once I have renamed the cookie to "CookieId3". Please tell me where i am going wrong.
As you can see, the method is not static. Thank you
The issue appears to be the difference between Request and HttpContext.Current.Request when the code is accessed from a ClassLibrary.
Is anyone is able to shed some light on this?!
The following works.
public string GetUserCookieId()
{
string cookieName = "CookieId18";
HttpCookie userInfoCookies = HttpContext.Current.Request.Cookies[cookieName];
string cookieId = "";
if (userInfoCookies != null)
cookieId = userInfoCookies.Value;
if (string.IsNullOrEmpty(cookieId))
{
cookieId = Guid.NewGuid().ToString();
HttpCookie cookie = new HttpCookie(cookieName);
cookie.Value = cookieId;
cookie.Expires = DateTime.Now.AddDays(90);
HttpContext.Current.Response.SetCookie(cookie);
}
return cookieId;
}

Custom authentication doesn't work with asp.net 2.0

I'm trying to upgrade my mvc 1.0 application that had a custom written login. I assign the authcookie like this:
string _roles = string.Join(",", _ugr.GetUsergroupRoles(_username));
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
_username,
DateTime.Now,
DateTime.Now.AddHours(1),
false,
_roles,
"/");
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
HttpContext.Response.Cookies.Add(cookie);
When I debug I got _roles = "Admin"
And I have an actionfilter that overrides OnExecuting where I have:
..
string[] _authRoles = AuthRoles.Split(',');
bool isAuthorized = _authRoles.Any(r => filterContext.HttpContext.User.IsInRole(r));
if (!isAuthorized)
{
..
And here if I debug _authRoles has "Admin" in it, and isAuthorized is always false.
If I check the "ticket" it has some: UserData = "Admin".
What can be wrong there? Is it the "User.IsInRole" that is different, or do I need to add something in web.config?
/M
http://www.eggheadcafe.com/tutorials/aspnet/009e2e5e-5a44-4050-8233-59a0d69844e8/basics-forms-authenticat.aspx

Resources