Creating unique sessions per user on Webforms ASP.net - c#

We are currently developing a simple system on ASP.net which are going to be used by users simultaneously. What I want to happen is to get each users' Name (or any other useful info) from a SQL table every time they log in to the system and use this data all throughout (Note: this data should be unique per user).
Now my question is, what is the proper approach on this kind of scenario to give unique variable/session per user? And what if I want to make this variable a global one?
Sample Scenario: A doctor logs in to the system and the code behind gets his name from the table and prompts the data on the homepage - "Welcome Doctor John!" (assuming his name is doctor John. Another user logs in to the system, gets his name and prompts respectively, now the conflict arises if the first user - John, refreshes the page and this is the conflict that I want to avoid.
Any article that I could read on with regards the matter? Any help would be much appreciated.
Disclaimer: I am still a beginner when it comes to ASP.net so my apologies for such simple question.

Session is where you will keep this information. It will be unique for each user. Read more about it at: ASP.NET Session State Overview
Just remember, that Sessions are maintained on Server for each user. They are costly. So if you keep too much data in your session then you may end up claiming more resources on the server.
Consider the following example where you retrieve your UserInfo in an object from Database.
UserInfo userInfo = GetUserInfoFromDB();
To Store information in Session:
//once user is authenticated
//store session
Session["UserInfo"] = userInfo;
To Retrieve information:
UserInfo currentUserInfo = Session["UserInfo"] as UserInfo;
if(currentUserInfo != null)
{
//info found
// assign lable Text currentUserInfo.UserName etc
}
You may see: Exploring Session in ASP.NET - Code Project

Just use the Builtin Session Management. It is unique to the user.
The Session Management stores, by default, a cookie at the users browser
to identifiy them. Only a Session Id is stored at the users browser and the other information, in your case the name, is stored on the server. You can define a Session Database for example if you have multiple webservers and want a single point to store the data.
If you have a single webserver it is very easy to use out of the box.
Set a Session variable.
Session["UserName"] = yourUsernameVariable;
Retrieve a Session variable.
var userName = Session["UserName"];
Here are some tutorials.
A Beginner's Tutorial on ASP.NET State Management
Exploring Session in ASP.NET
ASP.NET Session State Overview

Related

Options for storing user information while logged in

What are some options in regards to maintaining user data while they are logged into my mvc4 site? I am building off of the Internet Application template and right now I am using User.Identity.Name to get the logged in user's username that they used to login with. I'd like to be able to also store and access several other pieces of information about the user across every page on the site. Can I still use User.Identity somehow and apply other attributes to it? I started building a ProfileModel that I could pass to views, but then I don't believe I would be able to pass other models to those views, not sure.
I'm open to suggestions as far as persistent user data, and thank you for any help.
EDIT 1: When I say persistent, I mean while they are logged in, the data itself is already stored in an external database, so I won't be doing any writing of this information, simply pulling it from the database, then holding onto it for the duration of them being logged in.
You'll want to leverage Session for that. Consider the following code:
Session["Profile"] = profileObj;
or maybe you just want to store a string:
Session["SomeSetting"] = value;
What you need to store in Session is unclear, and effectively irrelevant, you can store anything. You can access the Session from any Controller.
Then later on you can get the value out like this:
var profile = Session["Profile"];
// if the profile variable is null then it doesn't exist in Session yet
In response to #AaronLS, Session lasts the duration of the IIS session that's created when the user first accesses the site. Do keep in mind that these sessions are reset if inactive for a period of time (I believe the default IIS timeout is 20 minutes) so you'd want to leverage the null return value to know that you need to redirect the user to the login page to login again.

Session - Login to view user data

Before I start I would like to state that I am very VERY new to ASP.NET and C#, and programming in general really. I have created a web application with a login page looking to a custom database containing the user's data as well as their login details. I did this rather than using the ASP.NET Membership as there are complications using this over my college's network.
As the table contains many records of user data, what I would like to do is have a user log into the app and (based on their login details) allow them to view JUST their details from the table I have created as their are many records of user data.
Am I correct that I should create a session based on their username and password and with this, somehow match it to their record in the table using SQL which will display ONLY their data rather than the whole table be displayed?
If this is the case, I really don't have a clue how to implement this.
I am aware that this will be very insecure but the users are all fictional and this app will not be published to the web. I just want it to work in the simplest form for my assignment and I'll cover the security aspects in my report and state how it could be improved.
Any advice would be greatly appreciated, Cheers.
Whenever you find a user's credentials valid enough for login, add some/all of his credentials to the current session like,
Session.Add("sessionvariablename",textBoxLogin.Text);
On the other page, that comes after logging in, check the following,
if(Session["sessionvariablename"].ToString()=="xyz")
{
Do whatever you want
}
You may not want to add sensitive information to the session for security concerns. Use
Guid.NewGuid() to create a unique 32 character hexadecimal code for each user and store it in session.
You should have row in your table with with a unique identifier. Like ID or userNr or something similar, make it an integer and set to primary key and then set its identity specification (is identity) to yes by double clicking on it (I am presuming that you are using visual studio).
When the user has submitted there login info and they checked out, you save there unique identifier in a session.
when you need to pull out information specific to the user in question, you use sql WHERE ID (or userNr) is equal to the session id.
hope this is what you needed, its my first answer in here so I would like to be helpful.
If I'm getting it right, using username and password as session parameters will work but it's not the best idea. Normally you table with users contains a kind of unique identifier for each record (guid or autoincrement id). You may use this identifier as a session parameter.

Profile variables in asp.net tracking session with login control?

I have been making a web site with a cart in asp.net using visual studio 2010. My question is concerning the Profile variable and Login Control.
I followed a pretty straight forward tutorial to add a cart to my site.
1: Shopping Cart Example
As you can see in the shopping cart tutorial, the author used a Profile to keep track of the cart.
When I was making this, I had expected the cart to stay the same with each different user login since we were using a profile and not a session variable. Fortunately, the cart would in fact reset as I logged in as different users with the login control.
So my question is, how is the Profile keeping track of the cart for each user. I'm almost certain that the login-control does not set a session variable, so I don't think the Profile object is auto-detecting a different user from the login-control... is it?
Please help me understand this, the author isn't quite clear.
Thanks a lot!
Basically the way it works is by using the authentication information to identify the user. So when a request comes in from an authenticated user the framework uses the username (typically in the form of an authentication cookie) to load the profile information into the current request.
In the case of the example you provided because the author is using <anonymousIdentification enabled="true"/> which allows for profile information to be available for anonymous users as well.
When an anonymous user makes a request, the AnonymousIdentificationModule module creates a GUID and writes it into a persistent cookie named .ASPXANONYMOUS. This GUID will act as the username for the purpose of the ProfileProvider.
the important part of the code that brings together the cart and the Profile is at the very end (happens behind the scenes for every login):
void Profile_OnMigrateAnonymous(object sender, ProfileMigrateEventArgs e)
{
ProfileCommon anonymousProfile = Profile.GetProfile(e.AnonymousID);
if (anonymousProfile.SCart != null)
{
if (Profile.SCart == null)
Profile.SCart = new ShoppingCartExample.Cart();
Profile.SCart.Items.AddRange(anonymousProfile.SCart.Items);
anonymousProfile.SCart = null;
}
ProfileManager.DeleteProfile(e.AnonymousID);
AnonymousIdentificationModule.ClearAnonymousIdentifier();
}
You can read about Profiles etc on MSDN - for example: http://msdn.microsoft.com/en-us/library/ewfkf772.aspx
This is not quite entirely true about session. Sessions are used in a way to store certain information about logged in users. However information about logged in user (as set by asp:Login control after successful login) is also stored in a principal which you can access from HttpContext.Current.User object. Another location where information about users is stored is in the cookie named .ASPXAUTH cookie. So there are couple of locations from which user information can be retrieved. But Profile will rely on an object of type IPrincipal. As for the anonymous users, Peter Mourfield gave you a good answer so I will not repeat his words.

Usage of Session object in ASP.NET

I've just been given a new task to bootstrap a website created by someone else. But I'm absolutely new to Web. The website is in ASP.NET,C#. The code itself is not hard to understand except for the Session object. I don't understand where, how and why it's used.Could please someone explain the usage of Session object with a possible example?
P.S. What would these two lines mean?
lblPensValue.Text = sh.pensDec((string)Session["connSTR"], 113, 23);
and
if ((string)Session["connSTR"] == null)
Session is used to store data for the user's session on the web site. (this data store is per-user-browser session, and is subject to being wiped at any time by various application events)
It is generally used to store information across multiple page views in a user's session (ie. visit) to your website.
It can be used anywhere in code that runs in the context of the user's session; meaning inside a page, or in the appropriate application lifecycle events which run in the context of a session (such as Session Start)
As for your samples;
The first one, I can't fully explain, as I do not know what the function sh.pensDec() is supposed to do.
The second one is checking to make sure there is a value stored in that session variable, before running the code that follows.
HTTP by nature is stateless. The WebServer doesn't know any details after it processes the request and sends back to the client. Thus, any subsequent requests are like fresh requests to the server.
To Enable the Server to remember & subsequently recognize what it served to the client, ASP.NET uses various mechanisms of which Session is one of them.
Session is created per user. So, in your Page, you are fetching the "connSTR" are storing it. Whenever a subsequent request comes from the same user, by querying Session with the key
Session["connSTR"]
you get back its value. Since Session is an Object, its casted as a string in your code.
(string)Session["connSTR"] // Return value from session and casting to string
You need to understand Session, check this ASP.NET Session State Overview
ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application.
ASP.NET Session State Overview
ASP.NET Session State Examples
Look at, e.g.,
ASP.NET Wiki › State Management › Session
ASP.NET Session State Overview
the documentation for the HttpContext.Session Property

Asp.net Login - Working with user data

I'm making a simple page and i need a login interface for users.
I want users to login to the page and when he is logged in he gets alot of data from the database that is signed to him alone. I did this before using very simple datatable holding the username, crypted password and the uid. When the user logged in the site i set the uid into a session so i could use it when i was selecting from the database..
This is probably not a safe way....easy to crack ?
Better way would be using the asp.net login id...?
What is the best way to do this, should i have all the user info in the ASPNETDB.MDF, and does that database work when i deploy the site on a server ?
Can i use ASP.NET Configuration when i have deployed ?
[Edit]
How can i use the asp.net login to get the userid of the current logged user so i can do sql querys for him ?
I think you should read more on "ASP.NET authentication" - regarding how to implement user login/logout/get userid etc. And on "ASP.NET authorization" - regarding security and access and come back with certain questions. There's standard mechanism for this.
Start with MSDN:
http://msdn.microsoft.com/en-us/library/eeyk640h.aspx
http://msdn.microsoft.com/en-us/library/wce3kxhd.aspx
The ASP.NET membership provider will likely be your best approach as it handles all of the basic plumbing which you need. The tables are quick to setup with the ASP.NET SQL Server Setup Wizard (C:\Windows\Microsoft.NET\Framework\v2.0.50727\Aspnet_regsql.exe) and the combination of the Configuration pages and out of the box login controls will get you up and running quickly. I would recommend going down this path.
Regarding one of your specific questions, the logged in user's Id is stored in the ProviderUserKey. This is the value which maps to the UserId in the membership tables like aspnet_Users and others. Here's how you get the value:
using System.Web.Security;
//ProviderUserKey is an object.
//You will likely want to convert to string or Guid
MembershipUser user = Membership.GetUser();
Object userId = user.ProviderUserKey;
There really is nothing wrong with the way you are doing it, although there are easier methods to do it.
If you are creating a login hash, and storing it in session, the users have no access to that data.
When you create a session state, all that gets sent down in a cookie is a GUID that refers to their own session, and not any of the actual data. Because of this, you can generally assume the data is protected and users can't get access to anyone else's data.

Categories