On my login page the FormsAuthenticationTicket is set as a persistent cookie with some custom userdata. Now I need to change this custom user data, so it contains one more parameter. When a previously logged in user visit the site the next time, I deserialize this custom userdata in Application_PostAuthenticateRequest but now I won't contain the newly added paramter.
Can I retrieve this paramter, without the user is required to login once again?
And if not, how to tell to the persistent cookie that it needs to be 'updated'?
Cookie set. userId is a new parameter:
CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
serializeModel.FirstName = model.UserName;
serializeModel.userId = model.userId;
JavaScriptSerializer serializer = new JavaScriptSerializer();
string userData = serializer.Serialize(serializeModel);
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
model.UserName,
DateTime.Now,
DateTime.Now.AddYears(5),
model.RememberMe,
userData);
string encTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
faCookie.Expires = authTicket.Expiration;
Response.Cookies.Add(faCookie);
return RedirectToAction("Index", "Home");
Cookie retrieval. Userid is the new paramter, and is null for previous logged in users:
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
JavaScriptSerializer serializer = new JavaScriptSerializer();
CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData);
CustomPrincipal newUser = new CustomPrincipal(authTicket.Name);
newUser.FirstName = serializeModel.FirstName;
newUser.userId = serializeModel.userId;
HttpContext.Current.User = newUser;
}
Are you using web forms or MVC?
It looks like your setting your HttpContext.Current.User correctly. The problem may be that your by default that your controllers / views still thinks its IPrincipal and not your Custom Principal, So you can't access the new data you set.
You can cast it, or set it in a base controller like below.
// in some controller action
var firstName = ((CustomPrincipal)User).FirstName
[Authorize]
public class BaseController : Controller
{
protected virtual new CustomPrincipal User
{
get { return HttpContext.User as CustomPrincipal; }
}
}
Related
I have created a Website in ASP.Net MVC5 and used a login function in it, it works fine on localhost but when I uploaded the site server,
Server redirects me to the login page on each click.
Below is login Function
public ActionResult DoLogin(string username, string password)
{
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
{
var user = new UserRepository().GetAll()
.Where(u => u.UserName.ToUpper() == username.Trim().ToUpper()
&& u.Password == password).SingleOrDefault();
if (user != null)
{
FormsAuthentication.SetAuthCookie(user.UserName,true);
var authTicket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddHours(24), true, user.Roles);
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
HttpContext.Response.Cookies.Add(authCookie);
Session["Name"] = user.Name;
return RedirectToAction("Index", "Student");
}
}
ViewBag.ErrorMessage = "User Name or Password is incorrect";
return View("Login");
}
then I added the below function in Global.asax.cs File.
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket != null && !authTicket.Expired)
{
var roles = authTicket.UserData.Split(',');
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(authTicket), roles);
}
}
}
After that I have added [Authorize(Roles = "Admin")] before each Controller (Not before methods in Controller) I want to Restrict access to.
Now, whenever I login, It redirects me to Index Method of Student controller, after that I click on some other link it again takes me to the Login page. Sometimes it takes me to clicked link without taking me to Login Page. Whats the Problem with my code? it works fine on localhost.
You are assigning the auth ticket twice;
if (user != null)
{
//FormsAuthentication.SetAuthCookie(user.UserName,true); Remove it
var authTicket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddHours(24), true, user.Roles);
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
HttpContext.Response.Cookies.Add(authCookie);
Session["Name"] = user.Name;
return RedirectToAction("Index", "Student");
}
Also, I suggest you to don't store the roles in cookie because if the user role has been removed or added new one, you can't update them. So,
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket != null && !authTicket.Expired)
{
var roles = authTicket.UserData.Split(',');//fill it from database and it could be better to use cache mechanism for performance concern
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(authTicket), roles);
}
}
}
This is the code I use to store a cookie after user is authenticated.
var authTicket = new FormsAuthenticationTicket(
1,
Session["UserID"].ToString(), //user id
DateTime.Now,
DateTime.Now.AddDays(1), // expiry
true, //true to remember
"", //roles
"/"
);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
if (authTicket.IsPersistent) { cookie.Expires = authTicket.Expiration; }
Response.Cookies.Add(cookie);
What should I do next to retrieve this cookie when the user visits the site again ?
To get the cookie:
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
To get the ticket inside the cookie:
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
Typical way of doing it-- implement AuthenticateRequest in global.asax.cs...something like this....
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
// Get the forms authentication ticket.
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
var identity = new GenericIdentity(authTicket.Name, "Forms");
var principal = new MyPrincipal(identity);
// Get the custom user data encrypted in the ticket.
string userData = ((FormsIdentity)(Context.User.Identity)).Ticket.UserData;
// Deserialize the json data and set it on the custom principal.
var serializer = new JavaScriptSerializer();
principal.User = (User)serializer.Deserialize(userData, typeof(User));
// Set the context user.
Context.User = principal;
}
}
...then, whenever any of your code needs to access the current user, just get the context user:
var user = HttpContext.Current.User;
Link
I am trying to add an option to my web page, so that when a user logs in to have a 'remember me' option. To implement this I am trying to store the user data (name+password) in a cookie, but it's not working at the moment.
My code to store the cookie is:
int timeout = 525600;
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(model.UserName, true, timeout);
string encrypted = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Expires = System.DateTime.Now.AddMinutes(timeout);
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
FormsAuthentication.SetAuthCookie(model.UserName, true);
Request.Cookies.Add(cookie);
and on my logIn controller my code looks like:
HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
if (cookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
var userName = ticket.UserData;
}
The problem is that the userData cookie is always empty. What am I missing?
Try this.
Creating/Writing Cookies
Way 1
`HttpCookie StudentCookies = new HttpCookie("StudentCookies");
StudentCookies.Value = TextBox1.Text;
StudentCookies.Expires = DateTime.Now.AddHours(1);
Response.Cookies.Add(StudentCookies);`
Way 2
Response.Cookies["StudentCookies"].Value = TextBox1.Text;
Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1);
Way 3
Response.Cookies["StudentCookies"]["RollNumber"] = TextBox1.Text;
Response.Cookies["StudentCookies"]["FirstName"] = "Abhimanyu";
Response.Cookies["StudentCookies"]["MiddleName"] = "Kumar";
Response.Cookies["StudentCookies"]["LastName"] = "Vatsa";
Response.Cookies["StudentCookies"]["TotalMarks"] = "499";
Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1);
Reading/Getting Cookies
string roll = Request.Cookies["StudentCookies"].Value;
Deleting Cookies
if (Request.Cookies["StudentCookies"] != null)
{
Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(-1);
Response.Redirect("Result.aspx"); //to refresh the page
}
reference here
I am trying to use SimpleMembershipProvider for FormsAuthentication. Now this provider internally creates a FormsAuth cookie without any additional userdata.
I want to include some other information in the cookie such as UserId, Role, etc
I have implemented following-
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (isAuthorized)
{
var formsCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
var identity = new AppUserIdentity(string.Empty, true);
if (formsCookie != null)
{
var cookieValue = FormsAuthentication.Decrypt(formsCookie.Value);
if (cookieValue != null && !string.IsNullOrEmpty(cookieValue.UserData))
{
var cookieData = SerializerXml.Deserialize<UserNonSensitiveData>(cookieValue.UserData);
identity = new AppUserIdentity(cookieValue.Name, cookieData.UserId, true);
}
else if (cookieValue != null)
{
//TODO: Find out technique to get userid value here
identity = new AppUserIdentity(cookieValue.Name, null, true);
}
}
var principal = new AppUserPrincipal(identity);
httpContext.User = Thread.CurrentPrincipal = principal;
}
return isAuthorized;
}
}
This attribute is decorated on all required controller methods. When a user registers or login on the website I am updating the cookie as well with additional userdata (serialized string)
var newticket = new FormsAuthenticationTicket(ticket.Version,
ticket.Name,
ticket.IssueDate,
ticket.Expiration,
ticket.IsPersistent,
userdata,
ticket.CookiePath);
// Encrypt the ticket and store it in the cookie
cookie.Value = FormsAuthentication.Encrypt(newticket);
cookie.Expires = newticket.Expiration.AddHours(24);
Response.Cookies.Set(cookie);
However, in MyAuthorizeAttribute it never gets userdata in the cookie. Is there anything wrong in the above code? Or something missing somewhere else?
Found the answer to this question,
check out the link
http://www.codetails.com/2013/05/25/using-claims-identity-with-simplemembership-in-asp-net-mvc/
In my application I use form authentication. My Authenticaton code is below:
public static void Authenticate(bool redirectToPage, ISecurityUser user, params string[] roles)
{
FormsAuthentication.Initialize();
GenericIdentity id = new GenericIdentity(user.UserName);
ExtendedPrincipal principal = new ExtendedPrincipal(id, user, roles);
//ExtendedPrincipal principal = new ExtendedPrincipal(id, user, new string[] { "1" });
string compressedPrincipal = ConvertPrincipalToCompressedString(principal);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddMinutes(30), true, compressedPrincipal, FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
//cookie.HttpOnly = false;
//cookie.Expires = DateTime.Now.AddMinutes(30);
HttpContext.Current.Response.Cookies.Add(cookie);
if (redirectToPage)
{
HttpContext.Current.Response.Redirect(FormsAuthentication.GetRedirectUrl(user.UserName, true));
}
}
The user object contains FirmID and DealerID properties. After I login to application, I can replace FirmID and DealerID from the app. After changing process this code is runned:
public static void RefreshIdentitiy(ISecurityUser user)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
ExtendedPrincipal principal = ConvertCompressedStringToPrincipal(ticket.UserData);
principal.BindProperties(user);
FormsAuthenticationTicket newticket = new FormsAuthenticationTicket(
ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration,
ticket.IsPersistent, ConvertPrincipalToCompressedString(principal), ticket.CookiePath);
cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(newticket));
HttpContext.Current.Response.Cookies.Add(cookie);
}
My problem is that: When I open the app from second page, cookie of second page crushes the first page's. So FirmID and DealerID of first page is also changed.
When I open app from second page, I don't want cookie to crush another. What can I do about this issue?
you should do something like this on all your pages:
if(Request.Cookies[FormsAuthentication.FormsCookieName]!=null)
{
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
cookie.HttpOnly = false;
cookie.Expires = DateTime.Now.AddMinutes(30);
HttpContext.Current.Response.Cookies.Add(cookie);
}
Edit
My aim is to make sure you are not overwrite your cookies every time you go to a new page