Store Id after authentication ASP net web forms - c#

I would like to save the user ID after the forms authentication is made through email and password. I am currently using a session to do so;
However the session and the form authentication have different timeouts and because the session is a server type of variable when one user is logged in if I login with a different username on another machine the session simple changes its value and that is a major issue.
Besides Caching is there any other way to accomplish it?

You can store user ID in expanded authentication cookie. On authorization routine compose custom cookie and add it to response:
var ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(60), false, userId.ToString()));
HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)) { HttpOnly = true });
You can decrypt that cookie for authenticated request and find out what was user ID:
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
int iserId = int.Parse(authTicket.UserData);

Related

Combine server-side and client-side authentication with WebAPI

I have a legacy ASP.NET webforms application in which users login via a form that is processed server-side. If the entered username + password match to credentials in the database, I set some values in the sessions (e.g., the current user ID) and perform a Response.Redirect afterwards. I'm also creating a HttpCookie for a "automatically relog me next time I visit" functionality.
Currently, I'm also adding WebApi support into that web application. I've managed to implement token authentication which allows me to login on the client side.
How can I combine both authentication approaches? I want to the user to enter his credentials once, get authenticated on the server side and on the client side an redirect the users to another page after authenticating.
The following code will create a cookie to keep user logged in.
// login etc
if (chkRemember.Checked)
{
// calculate the total number of minutes in 20 days to use as the time out.
int timeout = (int)TimeSpan.FromDays(30).TotalMinutes;
// create an authentication ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(txtUserName.Text, true, timeout);
// Encrypt the ticket
string encrptedTicked = FormsAuthentication.Encrypt(ticket);
// create the cookie for the ticket, and put the ticket inside
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrptedTicked);
// give cookie and ticket same expiration
cookie.Expires = ticket.Expiration;
// Attach cookie to current response. it will now to the client and then back to the webserver with every request
HttpContext.Current.Response.Cookies.Set(cookie);
// send the user to the originally requested page.
string requestedPage = FormsAuthentication.GetRedirectUrl(txtUserName.Text, false);
Response.Redirect(requestedPage, true);
}
else
{
// login without saving cookie to client
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false);
}
You can use token based authentication in webapi using Angular JS. Visit following link
http://www.dotnetcurry.com/aspnet/1223/secure-aspnet-web-api-using-tokens-owin-angularjs

AuthorizeAttribute not recognizing AuthCookie in ASP.NET

Upon successful Login I have this line
FormsAuthentication.SetAuthCookie(a.username, true);
Then I have several pages which require login to be accessed, so I added the [Authorize] attribute to them like so
[Authorize]
public ActionResult Upload()
{
return View();
}
However, after logging in, such functions still return a 401 - Unauthorized error page just as if the user had not logged in. The error page states:
Logon Method Anonymous
Logon User Anonymous
Furthermore, in my project Anonymous Authentication is enabled and Windows Authentication is disabled.
I am looking for a solution where funcitons like Upload() are always available to any logged in user.
What you can do and what I've done is to write your own cookie this way:
FormsAuthenticationTicket authTicket = new
FormsAuthenticationTicket(1, //version number of ticket
userName, // UserName
DateTime.Now, //cookie creation time
DateTime.Now.AddHours(24), //Expiration time . cookie valid for 1 day
true, //Persistent
userData); // other data to store in ticket
// set Cookie
Response.SetCookie(
new HttpCookie(
FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(authTicket)) //// encrypt ticket
{
Expires = DateTime.Now.AddHours(24),
HttpOnly = true,
Secure = FormsAuthentication.RequireSSL
});
"Forms authentication needs to be enabled, look in your web.config if you have in system.web" – glacasa

How to populate user(Identity) roles for a Web application when roles are stored in a SQL Server database

I have a C# based asp.net application which does a form based authentication and also needs authorization.
Here is the simplified version of the User table (SQL Server)
UID UName PasswordHash Userroles
----------------------------------------------
1 a GERGERGEGER Proivder;Data Entry
2 b WERGTWETWTW HelpDSK; UserNamager
...
...
I'm quite familiar with the Authentication part. But for Authorization I am not sure what is the best way:
I know once user is Authorized, you can use the Identity object to get his/her info.
The question is what my choice to read the logged in user's roles on every page other than call that DB table every time to get them?
I am not sure this is a SQL Server question. This is an ASP.NET question.
ASP.NET forms authentication allows the application to define a "Principal" which (among other things) contains an array of strings known as "roles." You can populate the roles from the DB one time (when the user signs on) then serialize the principal into the forms authentication ticket, which becomes an encrypted cookie on the browser. ASP.NET decodes the cookie with each http request and provides it to your ASP.NET c# code via HttpContext.User. It can then retrieve the roles from context and never needs to talk to the DB again.
Storing the roles would look something like this:
string roles = "Admin,Member";
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
userId, //user id
DateTime.Now,
DateTime.Now.AddMinutes(20), // expiry
false, //do not remember
roles,
"/");
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookie);

c# Update Cookie, without forcing the user to login

I have a 'UI' setting that controls the appearance, which the user can change the setting, however it involves updating the cookie.
I seem to be able to update, but it forces the user to authenticate again, how can i update the cookie without getting the user to autenticate again?
//We need to update the userToken as the menuOptionChanged
var usertoken2 = new UserToken(schedule.MinimisedMenuBool);
HttpCookie cookie = FormsAuthentication.GetAuthCookie(usertoken.UserName, false);
var ticket = FormsAuthentication.Decrypt(cookie.Value);
var newticket = new FormsAuthenticationTicket(ticket.Version,ticket.Name,ticket.IssueDate,ticket.Expiration,false,usertoken2.CalculateRawToken(),ticket.CookiePath);
// Encrypt the ticket and store it in the cookie
cookie.Value = FormsAuthentication.Encrypt(newticket);
System.Web.HttpContext.Current.Response.Cookies.Set(cookie);
Why are you saving UI appearance preferences in the authentication cookie?
Is there anything wrong with just saving it as a separate cookie?
HttpCookie menuCookie = new HttpCookie("menuCookie");
menuCookie.Values.Add("menuAppearance", schedule.MinimisedMenuBool);
menuCookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(menuCookie);
Then you can optionally only parse that cookie for logged in users.

Check if currently logged in user has persistent authcookie

I need to edit userdata in an a FormsAuthentication AuthCookie of the currently logged in user. I don't see how to find out if the current user has chosen a persistent cookie ("Remember Me").
//user is already logged in...
HttpCookie authCookie = FormsAuthentication.GetAuthCookie(username, ispersistant); //how to I determine 'ispersistant'?
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, NEWuserdata);
authCookie.Value = FormsAuthentication.Encrypt(newTicket);
HttpContext.Current.Response.SetCookie(authCookie);
Anybody got any ideas?
Thanks
The FormsAuthentication.GetAuthCookie method only creates a new cookie. It does not get you the earlier made cookie.
On your login page you probably have something like this:
FormsAuthentication.GetAuthCookie (userID, chkPersistCookie.Checked)
And to know when the user is authenticated you can do
this.Context.User.Identity.IsAuthenticated
I actually don't know for sure if you can deduce the fact that the user has a persistent auth cookie. One thing is checking the cookie for a expiry date.
In this question there is a example for reading the authentication cookie.
This should retrieve the existing forms auth cookie, examine the ticket, and tell if it's persistent.
var FormsAuthCookie = Response.Cookies[FormsAuthentication.FormsCookieName];
var ExistingTicket = FormsAuthentication.Decrypt(FormsAuthCookie.Value);
bool IsPersistent = ExistingTicket.IsPersistent;
I ended up storing "ispersistant" in the userdata property of the authcookie on login.

Categories