I am trying to create and read a forms authentication cookie in a c# web app that I am developing.
I create the ticket
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, "myData", DateTime.Now, DateTime.Now.AddMinutes(60), true, "Hello");
// Now encrypt the ticket.
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName,encryptedTicket);
// Add the cookie to the outgoing cookies collection
Response.Cookies.Add(authCookie);
Then when I retrieve the ticket using:
HttpCookie authCookie = Context.Request.Cookies[cookieName];
FormsAuthenticationTicket authTicket = null;
authTicket = FormsAuthentication.Decrypt(authCookie.Value)
I can see authTicket now has all of the data, cookie creation date, expiration date, name="mydata"... etc.
But there is nothing in the dataValue... I am expecting "Hello" to be there.
When I debug, I can see it is in the ticket right before encryption... it is getting lost in the decryption I suppose?
Any Help?
In order to set the cookie you use the FormsAuthentication.FormsCookieName property while when you read it you use the cookieName variable. Are you sure that both point to the same cookie? Also verify with FireBug that the value in the cookie is the same as the one you see when you debug.
Try using SetAuthCookie(authCookie) instead of REsponse.Cookies.Add(authCookie).
http://msdn.microsoft.com/en-us/library/aa480476.aspx
Related
Using : https://github.com/apereo/dotnet-cas-client
We can successfully see a proxy ticket in the logs generated but when accessing the the field 'ProxyGrantingTicket' it's always empty.
ICasPrincipal p = HttpContext.Current.User;
p.ProxyGrantingTicket
We can see the ticket in the cache, but assumed there would be a method to access it.
This works but would like to know if theres an inbuilt fucntion for this.
// Retrieves the cookie that contains your custom FormsAuthenticationTicket.
var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
// Decrypts the FormsAuthenticationTicket that is held in the cookie's .Value property.
var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
var ticket = HttpContext.Current.Cache["CasTicket::" + authTicket.UserData] as CasAuthenticationTicket;
ticket.ProxyGrantingTicket
Or slightly more streamlined way...
var formTicket = CasAuthentication.GetFormsAuthenticationTicket();
var ticket = CasAuthentication.ServiceTicketManager.GetTicket(formTicket.UserData);
Is CasAuthentication.ProxyTicketManager.GetProxyGrantingTicket(string proxyGrantingTicketIou) not working?
On a login form I have an option to allow the user to click a remember me checkbox which creates a new FormsAuthenticationTicket which then gets added to a cookie.
if (_model.RememberMe)
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
_model.Username,
DateTime.Now,
DateTime.Now.AddDays(30),
true,
_model.Username,
FormsAuthentication.FormsCookiePath);
// Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(ticket);
// Create the cookie.
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
Which should hopefully be in the clients browser for 30 days as stated above.
Testing this, I've purposely left the current session timeout for only a minute
<sessionState timeout="1"></sessionState>
So after a minute, if the user has said "remember me" I expect the website should not be redirected back to the login page. However it does. This is the code that does it.
// [".ASPXAUTH"] is the cookie name that is created by the FormsAuthenticationTicket`
if (User.Identity.Name == "" && Request.Cookies[".ASPXAUTH"] == null)
{
return RedirectToAction("LogOut", "Login");
}
// the current session hasn't timed out or the remember me cookie is enabled
FormsIdentity id = (FormsIdentity)User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
But the cookie is NULL.
I am expecting it's a misunderstanding on my behalf so if anyone can give me a hand. I would be very grateful.
Thanks
What you are looking for is
string mySessionCookie = System.Web.HttpContext.Current.Request.Headers["Cookie"];
if (mySessionCookie.IndexOf(".ASPXAUTH", StringComparison.Ordinal) >= 0) {
// do something
}
EDIT
How about this, I haven't tested it but I remember doing something like this before
HttpCookie cookie = (HttpCookie)(Request.Cookies[FormsAuthentication.FormsCookieName]);
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
I'm using C# and MVC5 to create my own cookie using this code:
// Prepare the ticket
HttpContext.Response.Cookies.Clear();
FormsAuthenticationTicket ticket =
new FormsAuthenticationTicket(1,
"MYNAME",
DateTime.Now,
DateTime.Now.AddDays(10), // <<- Expires 10 days
true,
null);
// Encrpt the ticket
string encryptedCookie = FormsAuthentication.Encrypt(ticket);
// Create new cookie
HttpCookie cookie = new HttpCookie("MYNAME", encryptedCookie);
cookie.Path = FormsAuthentication.FormsCookiePath;
// Send the Cookie back to the browser
HttpContext.Response.Cookies.Add(cookie);
On the Web.Config I set the name to be
<authentication mode="Forms">
<forms name="MYNAME" loginUrl="~/Account/Login"></forms>
</authentication>
But when I look the Firebug, the Cookie appears as "MYNAME" but the "expires" is set to Session.
And in fact, when I close the browser, the cookie disappears and when I go back to the site, I always have to login again. The same happens with all other browsers.
What am I doing wrong??
The problem was that I was setting the Expiration at the "Ticket" level but NOT at the "Cookie" level.
Adding
cookie.Expires = ticket.Expiration;
..solved the issue !!
So the entire code should look like this:
// Prepare the ticket
HttpContext.Response.Cookies.Clear();
FormsAuthenticationTicket ticket =
new FormsAuthenticationTicket(1,
"MYNAME",
DateTime.Now,
DateTime.Now.AddDays(10), // <<- Expires 10 days
true,
null);
// Encrpt the ticket
string encryptedCookie = FormsAuthentication.Encrypt(ticket);
// Create new cookie
HttpCookie cookie = new HttpCookie("MYNAME", encryptedCookie);
cookie.Path = FormsAuthentication.FormsCookiePath;
// THE MISSING LINE IS THIS ONE
cookie.Espires = ticket.Expiration; // <<- Uses current Ticket Expiration
// Send the Cookie back to the browser
HttpContext.Response.Cookies.Add(cookie);
How it goes with other browsers? Chrome, IE?
If it works fine there, then it should be working on FF as well.
If it doesn't work there then possibility is there is issue with code
Take a look on these articles
FormsAuthenticationTicket expires too soon
Basic one
http://www.codeproject.com/Articles/244904/Cookies-in-ASP-NET
http://msdn.microsoft.com/en-us/library/ms178194.ASPX
Thanks
I have an asp.net single page web application.
When the user enters to me web application , it gets a login screen with username password and I make an ajax call for authentication:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
"CookieName",
DateTime.Now,
DateTime.Now.AddMinutes(1),
true,
"data",
FormsAuthentication.FormsCookiePath);
// Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(ticket);
HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
Before any ajax call I check if the request and the user are authenticated:
if (HttpContext.Current.Request.IsAuthenticated)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
//do something
}
}
but when the cookie is expired, I still get "true" for both conditions.
Why? Is it because I make an ajax call?
Should I check if the cookie expired before every call instead of using IsAuthenticated?
I'm setting up mixed mode authentication in a C# web app. I set the AuthCookie in the WindowsAuthentication website and then try to redirect to the FormsAuthentication website. I think the cookie is in the correct path and everything because Context.Request.IsAuthenticated is true. Unfortunately, I keep getting redirected to the login page of the FormsAuthentication website as if I haven't set the AuthCookie. What is going on?
I'm not familiar with how authentication works in ASP.NET so please, explain it to me like I'm 5. Thanks, :)
edit: Here is the event in the Global.asax of the WindowsAuth site that makes the cookie. This site currently resides in the path /authentication "under" the FormsAuth site.
void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
WindowsIdentity ident = WindowsIdentity.GetCurrent();
WindowsPrincipal p = new WindowsPrincipal(ident);
if (p.Identity.IsAuthenticated)
{
HttpCookie cookie = FormsAuthentication.GetAuthCookie(p.Identity.Name, false);
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
// Store roles inside the Forms cookie.
FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(
ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration,
ticket.IsPersistent, "", ticket.CookiePath);
string encTicket = FormsAuthentication.Encrypt(newTicket);
Context.Response.Cookies.Add(new HttpCookie(".GWBTroubleTickets", encTicket));
}
Response.Redirect("/employee/home.aspx");
}
The event may be called many times per page. - https://stackoverflow.com/a/5947309/57883
You don't have an if/else surrounding the Response.Redirect("/employee/home.aspx");
Try using a custom attribute instead of this event