I have an ASP .Net 4.5 MVC website where I have customized the forms authentication following this tutorial. The difference is that I'm authenticating via a backend dll, so I have skipped all the database-stuff in the tutorial and where the tutorial fetches the user from the database I get it from a regular method call. I have followed this tutorial before and successfully implemented it in a new MVC website. This time I have implemented it on an existing MVC website, and I cannot get it to work.
When the cookie is added to Response.Cookies
it only exists until the code returns a View to the user. After that it does no longer exist in Response.Cookies
and this means that in the Global.asax Application_PostAuthenticateRequest
method, var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
always returns null
.
I have tried to add other simple cookies and these persist as expected.
This is how I add the forms authentication cookie
CustomUser user = service.GetUser(username, password);
if (user != null)
{
var serializeModel = new CustomPrincipalSerializeModel
{
UserName = user.UserName,
UserId = user.Id
};
var userData = JsonConvert.SerializeObject(serializeModel);
var authTicket = new FormsAuthenticationTicket(1, user.Id, DateTime.Now, DateTime.Now.AddMinutes(30), false, userData);
var encryptedTicket = FormsAuthentication.Encrypt(authTicket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) { Expires = DateTime.Now.AddMinutes(30) };
Response.AppendCookie(cookie);
}
And if I change this line
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) { Expires = DateTime.Now.AddMinutes(30) };
To
var cookie = new HttpCookie("test", "testing") { Expires = DateTime.Now.AddMinutes(30) };
Then the "test" cookie will act as expected and I can get it in Global.asax Application_PostAuthenticateRequest