Where to store user data after logging in using WebForms

I am developing a WebForms web application from VS2010 in C #. I use my user login approach to authenticate users and I don't want to use a membership structure. After logging in, I want to store user data as userId, username, last name, email address, etc. Therefore, I can access them during a user session on all pages.

How can i do this? I do not want to store user data in the UserData FormsAuthenticationTicket property.

I found this approach: Should I store user data in a session or use a custom profile provider? but I don’t understand how to implement it.

I have a question:
1) on my login page for user authentication after checking credentials on db I use: FormsAuthentication.SetAuthCookie (txtUserName.Value, true); now on my default page I have:
FormsAuthenticationTicket ticket = ((FormsIdentity) (User.Identity)). Ticket and I use ticket.Name to show username. it is right? why are you talking about thread using Thread.CurrentPrincipal.Identity.Name?
2) I have this code in the global.asax file for reading user roles and storing them in HttpContext:

void Application_AuthenticateRequest (object sender, EventArgs e) {

  if (Request.IsAuthenticated) { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnStr"].ConnectionString); conn.Open(); SqlCommand cmd = new SqlCommand("SELECT Gruppi.Name FROM Ruoli INNER JOIN Gruppi ON Ruoli.GroupID = Gruppi.GroupID INNER JOIN Utenti ON Ruoli.UserID = Utenti.UserID AND Utenti.Username=@UserName ", conn); cmd.Parameters.AddWithValue("@UserName", User.Identity.Name); SqlDataReader reader = cmd.ExecuteReader(); ArrayList rolelist = new ArrayList(); while (reader.Read()){ rolelist.Add(reader["Name"]); } // roleList.Add(reader("Name")) string[] roleListArray = (string[])rolelist.ToArray(typeof(string)); HttpContext.Current.User = new GenericPrincipal(User.Identity, roleListArray); reader.Close(); conn.Close(); } } 

Is it possible to store user data in a session, as you wrote from my global.asax file, and not the login.aspx page?

+4
source share
3 answers

In the interest of simplifying debugging, I suggest using the Session Facade design pattern described here , which will allow you to save the current data user using the HttpContext.Current.Session object HttpContext.Current.Session more organized way.

For example, there will be a file (for example, SessionFacade.cs ) that is responsible for processing the values ​​passed to / from Session ; in your case, it might look like this:

 public static class SessionFacade { public static int UserId { get { if (HttpContext.Current.Session["UserId"] == null) HttpContext.Current.Session["UserId"] = 0; return (int)HttpContext.Current.Session["UserId"]; } set { HttpContext.Current.Session["UserId"] = value; } } // ... and so on for your other variables } 

Then, somewhere else in your code, once you check that the credentials are ok, you can do ...

 if (credentialsAreOk) { SessionFacade.UserId = /* insert ID here */ // ... } 

... instead of manually assigning values ​​to the Session object. This ensures that your variables in Session are of the correct type and will be easier to track when debugging. Then, to get a UserId from anywhere in your program, it's just SessionFacade.UserId .

(yes that the snippet was with Edward's answer, you should still look at this answer as it is informative about how WebForms works, just keep in mind that calling a Session object manually in the code can be quite dirty, and that the Session Facade does this process is cleaner)

+4
source

In the case of “VS2010 web application in C #” you are talking about ASP.NET (MVC or Classic) and “user-friendly approach”, you mean FormsAuthentication , then you only need to save your necessary information during login system on Session .

Let's say you use ASP.NET Classic and you have a login page

enter image description here

which has 2 inputs for username and password and a submit button called "Login"

enter image description here

In the OnClick event handler (server side) you should do something like this:

 public partial class Login : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } private bool CheckUserPass(string username, string password) { // access DB or some other form of storage service return true; } protected void buttonLogin_Click(object sender, EventArgs e) { bool credentialsAreOk = this.CheckUserPass( this.textBoxUsername.Text, this.textBoxPassword.Text ); if (credentialsAreOk) { this.Session["EMAIL_ADDRESS"] = " SomeEmail@SomeEmailProvider.com "; this.Session["OTHER_INFORMATION_KEY"] = "Some other stuff which you have access to during the login process"; this.Session["TIME_OF_LOGIN"] = DateTime.UtcNow; FormsAuthentication.RedirectFromLoginPage(this.textBoxUsername.Text, createPersistentCookie: false); } } } 

So, in short, if you use FormsAuthentication, you can save the username in the session just as you tell FormsAuthentication that the current session should be converted from unidentified to authenticated:

 FormsAuthentication.RedirectFromLoginPage(this.textBoxUsername.Text, createPersistentCookie: false); 

while other information can be placed in the Session object (just as you would add key value pairs to the dictionary):

 this.Session["TIME_OF_LOGIN"] = DateTime.UtcNow; 

It is obvious so far that you can later access the same information (for the corresponding user):

 DateTime whenDidILogin = (DateTime) this.Session["TIME_OF_LOGIN"]; // this line of code can be used in any other page // at any later time - it like you have a global set of variables // which exist for each and every distinct session you might have 

perhaps it’s important to note that the username (if it is not explicitly placed on the Session object, like other examples), can be accessed using Thread.CurrentPrincipal static like this:

 using System.Threading; public void SomeWhereInYourApp() { bool wasIAuthenticated = Thread.CurrentPrincipal.Identity.IsAuthenticated; string whatIsMyUsername = Thread.CurrentPrincipal.Identity.Name; // do something with that information } 
+3
source

The membership provider helps store data as well for authentication purposes. Something like that: -

 Session["UserName"] = Membership.GetUser().UserName 
0
source

Source: https://habr.com/ru/post/1495568/


All Articles