ASP.NET Sessions in C# - c#

My goal here is to properly assign a session and retrieve the value stored in that session.
When users come to my first page, a Default.aspx page, I set the session in the code behind.
HttpContext.Current.Session["permissions"] = "Super";
However, I am unable to access this section in a Data Access Class in another file. Am I doing something wrong, or does anyone know a correct way of accessing an already set session from a C# class?
I try to access the session using the same syntax:
String permission = HttpContext.Current.Session["permissions"].ToString();

I am pretty sure , that you can always override this situation. What you are trying to do is not considered a good design principal.
what you can do is to pass the CurrentUser and/or his/her role to the data class by populating a custom property on that class. Within that class you can use the value of this property to work on the user's role.
let me know , if this helps you.
For code samples , you can always look at this SO question
How to access session variables from any class in ASP.NET?

Related

Alternate for Session variable in c #, Can we use class and its object to store a value instead of session variable?

I am building a web application. The authentication will be managed by the website, that is not my concern. What i need to store is the UserID in some place.
Once they open the application I will be able to get their UserID. I was previously using a Session variable to store this. Can I create a class say:
static string _UserID;
public static string UserDetails
{
get
{
return _UserID;
}
set
{
_globalValue = \\value from webpage;
}
}
and use UserDetails._UserID instead of assigning it to a session variable?!
The website's session server is not very reliable so I thought I could use this way.
Will this work?
I learnt from the answers that the variables will be overwritten for each user which is not what I want!!
Will it be the same scenario if i create an instance of this class in handler and assign the UserID to it??
are there any other way where I can make its scope limited only to one user i.e UserID with which I login should be same and if new user login to the application it must not be overwritten?? what is the disadvantage of using this method??
Is this method good if I use only one page and assign the object in the launch of the applciation ??
Static variables persist for the life of the app domain. So the two things that will cause your static variables to 'reset' is an app domain restart or the use of a new class.
The main problem is that static variables are shared across ALL USERS, and that is dangerous in your case that you pretend to store an UserID inside it. If you want to store
per user sessoin ID you should use Session
You can find more info here:
Lifetime of ASP.NET Static Variable
static filed will be shared between all users that means you would overwrite it for everyone. If you do not want to store it in Session you may store it in cookie (encrypted if security is important).

Custom Roles/Permissions in ASP.NET

I currently have a Web Application which is using it's own "Permissions" table which contains the following columns:
UserName - Windows UserName (Context.User.Identity.Name)
DivisionID - Links to a Division Table
RoleID - Comes from a custom Roles Table
RegionID - Recently added field to divide my Application into Countries (Canada, USA, International)
When the User logs into the site, they choose which Region they want to enter and I need to give them access to those Regions based on if they have any permissions set for that specific RegionID. Upon selecting a Region, the RegionID is stored in Session and will be used for this permission check and defining how data is populated on the pages (I haven't implemented the Session variable into all of the pages just yet so that can be changed if need be)
My initial thought would be to run my Permission Check on each page sending them to one of three destinations:
Invalid Permission Page (false)
Region Select Page - No Region selected in Session (RegionID = 0)
The page they requested - If has a permission set for that Region
I've also looked into using the Application_AuthenticateRequest method within the Global.asax but I cannot use Session within this area and it seems to be hitting the Application_AuthenticateRequest much more than it should be.
With my current App, what would be the best way to authenticate each user with their corresponding Regions, based on their Permissions?
I've really only worked with forms authentication-- but I'm assuming you'll be using windows authentication for membership and some form of custom roles authentication. I've never done it, but one would think it should work.
http://msdn.microsoft.com/en-us/library/system.web.security.roleprovider.getrolesforuser
You could create a custom provider that would take into account the Session value for Region in order to return the correct roles. I know for a web application, the default provider stores the roles as an encrypted cookie on the client. I'm thinking you can do something similar.
Normally I wouldn't recommend this method, but as it seems that you have already developed your application, you could relatively easily implement the following without too much upheaval:
Create a base class for your pages, and then inherit all the pages in your application from the base class. You would of course implement the "authorization" within the base class.
The one rather nasty problem with this is that if you forget to derive your page from the base class, then your page has no security on it.....but you could just as easily forget to implement your "Permission check"....
Something like
public class AuthorizedPage: System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
// ... authorization logic here...
// Be sure to call the base class's OnLoad method!
base.OnLoad(e);
}
}
You could check this out ASP.net "BasePage" class ideas and this https://web.archive.org/web/20211020133935/https://www.4guysfromrolla.com/articles/041305-1.aspx
Or, another idea, if you have used Master Pages you could also just do this stuff in the master page....

Global Variable inside of Controller MVC

So, I have this variable that I push into the controller via POST from a form in my view.
I then push the variable into viewdata so it's available to the next view which is fine. But that view has no need of a form so I'm unable to push that same variable into the next controller. In short, it's cumbersome to push pieces of information back and forth from controller to view and reverse, so I'm looking for a way to keep a global variable alive inside a controller so that it's accessible by all action results... The general breakdown of my program is this...
-User types a "name"
-I send "name" to controller.
-I push 'name' into viewstate (query entity framework to get a list of stuff 'name'
has access to) and return that list into the view.
-In that view I can access the 'name' since it was in view state.
-Clicking on a link inside the page takes me to another controller where I need
to get access to 'name' WITHOUT passing view Routing or POST.
Obviously the easiest way would be to declare 'name' globally and then it's always available but for the life of me I can't figure out how.
Have you considered storing it in the Session?
This will allow you to easily access it, either from your controller or views, and avoids the need for global variables.
Storing:
[HttpPost]
public ActionResult YourPostMethod(string name)
{
Session["Name"] = "yourName";
}
Access: *
Make Sure to check that it exists prior to grabbing it:
var whatsMyName = (Session["Name"] != null) ? Session["Name"] : "";
Scalability Consideration
It's worth mentioning that MVC applications are designed to mimic the web and are stateless. Introducing Session variables changes this, so be aware that it can introduce issues regarding scalability, etc.
Each user that stores data within the Session will take up resources at the server level. Depending on the number of users and what you are storing within the Session, you could potentially run out of memory if those values become too large.
Why not use the session object, which is an associative array which lives while the client is connected?
$_SESSION['name'] = "zzzz"; // store session data
name = $_SESSION['name']; //retrieve data
You can use this for each user till their session is active.. hope this helps

SQL role security + custom ASP.Net base page

I'm workng on a new, green-field ASP.Net application. We're implementing a base page which all pages will be, er, based on. The application will be running under Integrate Windows Auth, so I'll have the user's account details. With these, I'll be going to several databases (in which the user will exist) to find out what roles they are assigned to in each db. I'll be holding the role yay/nay in a bool array, and key into it via an enum.
There will be a session object that will hold a few things, and the roles assigned for that user. I'm thinking of making the session object available as a property of the base page, as the code would be something like this:
public SessionObject MasterSessionObject
{
get
{
if (Session["SessionObject"] == null)
{
// Create session object, assign user name, etc.
// Do something with roles...
Session["SessionObject"] = sessionObject;
}
return (SessionObject)Session["SessionObject"]
}
}
In order to control what happens on the (sub-classed) page, I want to provide a CheckSecurity method - e.g. if the user is not authorised to a certain part of a page, it can be hidden / disabled, or they could be booted back to a "not yours" page. The logical place for it is the base page, but seeing as the base page is already exposing the SessionObject that holds the roles permissions, would it not make more sense to Create a DatabaseSecurity type object and have the check on that?
Dealing with the latter approach, I've used abstract base classes to get me so far: I have a DatabaseRoles abstract class which contains the bool array, and a method to retrieve the roles for the user. The concrete implementation holds an Enum (as previously mentioned) to key into the array (in the base class). The abstract class also has the CheckRole method which takes in an int, to which I'm intending use a cast of the enum...
The SessionObject contains several of these DatabaseRoles implementations, and essentially does away with the need for a CheckSecurity in the base page class, leading to code like this in the actual page:
if (MasterSessionObject.SampleDatabaseRoles.Check((int)SampleDatabaseRolesEnum.RoleView))
{
// Do something
}
But, I'm sure you'll agree, it looks sucky...
If there was a CheckSecurity method on the base page, it would have to take a concrete DatabaseRoles object, but also an enum of which role to check, which would also look sucky. And finally, there would be a requirement at a later date to add more databases and their security settings...
I'll add code tomorrow if required... :-s
I dunno, I'm not that thick, but I do have a hard time sometimes binding all this together...
Thank you,
Mike K.
IF you happen to use ASP.Net / ASP.Net MVC, I would say the best place to do this would be via a custom HTTP Module by handling the AuthenticateRequest method & continuing with the request only if the request has been authenticated. There are tons of excellent articles online for this code.
Also - have a look at the Roles & Memberships of ASP.Net - it is pretty good & generally satisfies most requirements or you are always free to extend it. Again - tons of articles on custom membership providers...
unless I am missing something - HTH.

Session Variable problems when storing an object in my Session

I have a log in page where I valid my users and based on this validation I store their user info in a session variable so I can access it at any time. To do this I am trying to store an instance of one of my dbml generated classes "UserInfo". So I populate the class and then store it in a session variable I call "user"
UserInfo u = new UserInfo();
u = dal.RetrieveUser(userID, userPass)
Session["user"] = u;
The issue I am having with this is it seems to mix up these session variables between users. Or more specifically it always seems to take the information from the first user variable stored for each subsequent user that logs in. So user 1's info is being pulled in for User 2, User 3, etc...
Is my problem that my class "UserInfo" is somehow static? Or what is causing this to happen? My UserInfo class looks like this:
public partial class UserInfo
{
...
EDIT:
After further review it seems that my Session variables are in fact working properly but my custom menus are actually the problem.
Sounds more like an issue with the DAL than the session object. Can you verify that the userID passed each time is different and the RetrieveUser function is using the passed value and not a static one?
Are you testing this using the web client on the same computer or separate computers? For instance, by default FireFox will run in a single process even if you have multiple windows or tabs open. As silly as it sounds, a colleague of mine had not noticed this phenomena when he had the same issue.

Categories