ASP MVC vs. WebForms: using SessionState for user logon - asp.net-mvc

i've a question regarding handling of user logon while porting an application to MVC:
in the "old" WebForm days, developers simply used the SessionState object to set a user to logged-on, by -for example- simply putting the userobject into the SessionState (and this userobject holds simple properties like name/lastlogon/etc.)
this stuff worked very well for us, and i've seen lots of applications doing it that way
yes, i know there is this MembershipProvide-thingy, but i've never used it
Now, in MVC, everybody tells me that "using SessionStat for this is bad" and "apps built that way are flawed in design" and that "there are tons of security risks" and so on.
I've used this method because it worked for the app very reliable, it was simple to implement and it covered all stuff we need.
(Sure, there is the thing with recycling web worker process and emptying the session - but thats not a problem in our case, since the app runs for each country on a dedicated machine)
I've read tutorials, telling me to put that stuff in the DB and -attention- doing a request to the DB to check if the user is logged in, per EACH request? But: Under no circumstances, this is a doable way since i want to keep DB requests on a minimum.
So my question is:
A) whats wrong using this way also in the new MVC app?
B) whats the best way to handle this scenario in a newly built MVC app?
Regarding the session-in-DB-idea: instead of doing this, i'd rater setup an additional service, like a "session-manager" thats get query over the network, but such simple requests should not go to the DB - isn't that a good idea?
Any idea, hint /etc. is highly appreciated since this scenario is really confusing me :-X

A)
A fundamental principal of the asp.net mvc framework is that its stateless. Data is passed around using http requests and sent to the views in viewmodels. Web forms tried to maintain state with viewstate etc thats why you would have seen the logged in user in session approach. Thats not to say session shouldnt be used completely in asp.net mvc, there are some circumstances when it can be useful. Like maintaining a 3 step form process that has to be persisted on the last step. But generally we already have a recommended way to handle the user logins, and thats forms authentication
B)
For accessing the user object, you can create a custom identity implementing the IPrincipal interface and add the required user fields you need. Then set the custom identity in a global filter and access it in your action results. Regarding not wanting to query the database for every request, why dont you just call it for the initial request, then cache the result until the user is updated where you then can reload the object and set it in the custom identity again.

Related

Why doesn't WebSecurity.Logout *immediately* update IPrincipal.User to null user

First of all it's important to note that in my application if you log out your session is still valid and you don't just get redirected back to a login page, but stay on the same page.
With that said - whichever of these two ways I use to sign out in an MVC application
FormsAuthentication.SignOut()
WebSecurity.Logout()
the effect is the same and neither of the following properties changes to reflect the logout if I immediately access them :
User.Identity.Name
Thread.CurrentPrincipal.Identity
Now - If I do a Redirect, or just reload the page then obviously these properties are updated to a null user. They just don't immediately meaning that User.Identity.Name represents a user that just logged out.
This is a problem because I want to generate text of the form You are logged in as XXX after login/logout - and this may be in an AJAX situation where a redirect isn't possible.
I'm curious if there's any way to trigger the IPrincipal to reset itself after a logout (or login).
I assume people normally just Redirect() after a Logout() call so this is never an issue, but in an AJAX situation this is not always practical.
My current solution is to abstract the Identity in my own wrapper, and so once I'm logged out I can just update that. I'm just a little concerned that this could have some obscure side effects especially if somebody accesses IPrincipal directly adn not through the wrapper.
This is a core limitation of the ASP.NET event pipeline as it relates to forms authentication. This also makes it vulnerable to replay attacks, as described in KB article 900111. In that article, they reference one solution to use a membership provider that stores some server-side information about the logged on user.
Membership provider seems very similar to the approach you are thinking of taking, and I wonder if you should consider using one of the built-in membership providers, or writing your custom code as a membership provider. This should address some of the concern about people not understanding the approach and calling the IPrincipal directly.
Your "logout but stay on the same page" brings the issue a little more to the fore, but ultimately you're just uncovering the same fundamental replay issue that everyone has with ASP.NET (but not everyone solves it).
This related question may also be helpful.

Asp Net MVC 3 - Moving through Actions and Views, SessionState

How can I keep some values between different Views in MVC 3?
I tried using TempData and HiddenField to keep these values but in our hosting this tecnique seems to have short life so exceptions are coming out furthermore if user uses Back button every starts to fail.
I would like to understand the better way to keep values between views in MVC 3, thanks in advice!
By design, MVC3 TempData values are removed after they are used.
The most simple answer is to use the Session object directly in your controllers.
There are other related questions with detailed answers such as these:
Session variables in ASP.NET MVC
Asp.Net MVC and Session
Your question is about the lifecycle of objects in between requests. It's important to understand that webapplications are used over the HTTP(S) protocol which is a stateless protocol. This means that every request is a completely new request for the webserver and there's no state shared between requests.
However it would be foolish to send the credentials of a user to the server each and every time so a webserver can create a thing they call a Session (and session-state). This object is an object that remains available for the lifetime of the session of the current user (most of the times from logging in until logging out). You can use this object to store items that you wish to share over various requests of the same user.
If the values you're trying to keep are specific to the page you can probably use a hidden field or something like that. However if the data is more related to the user than to a specific page and it must have a lifecycle longer than a single request then sessionstate is the best place to store the data.
You could use the Session (as you mention in your title and tags). Or store a cookie on the user's machine

asp.net mvc - membership provider

For my ASP.NET MVC app, I just find dealing with unique-identifiers harder, so I have added my own field to ASPNET_USERS table - UserIdInt (which is actually a bigint!) So most of user operations use userIdInt as reference.
Anyway, I am debating between two approaches:
1)When a user logs in, look up from the database and store the userIdInt in a session variable and any-time session variable slips away, re-look it up and put it back in session variable. (It's okay to use sessions in MVC app, right?)
2)Any time an operation needs to be performed, simply pass userName to database and take care of UserIdInt at database side by doing joins and such on ASPNET_Users table any time an operation from user needs to be performed.
I am heavily leaning towards 1)... but I want to make sure I am on right track.
I asked this question on Serverfault first, but I was told to ask this question here.
progtick,
you may be far better looking into the use of custom profile providers as this would allow you to leave the aspnet_* tables as is (which is a good idea in case a later version of sqlserver changes how they operate) plus offer the additional bebnefit of having a multitude of additonal profile related properties availabale to your application. i can't overstate enough the benefits in going down this track as i've found it very useful to have such an approach in both my standard asp.net apps as well as my mvc ones.
you can get a feel for what's involved in this by looking thro a couple of these links:
here's one on SO for starters:
Implementing Profile Provider in ASP.NET MVC
and one from my old mate, lee dumond:
http://leedumond.com/blog/asp-net-profiles-in-web-application-projects/
hope this helps
An alternative approach is to alter the forms authentication ticket to add your unique id to the data stored in the cookie. Then, by implementing a custom IPrincipal you can have your unique id available anywhere that the User object is available.

How should I do authentication in a ASP.Net MVC site?

I have a site which has an area that requires authentication. Right now I use the roles attribute on all the controllers in that area, and I run a query to retrieve that users ID, and all their settings.
It seems like a code or design smell to me that I am retrieving the userid and settings each time a controller in that area loads up? I'm not sure if I should be using sessions, or if ASP.Net MVC 2.0 provides some unique way to handle this. Another concern is security.
Overall, I don't really know which way to turn. Design wise I would like the userId and settings retrieved only once when the user logs into the area. Right now I grab the userId each time a controller loads up, and then if required, I query the database for their settings each time as well.
One of the rules about security is that you shouldn't try to do it yourself. There are many pitfalls in doing an authentication system correctly without leaving loopholes or backdoors. Thus, in that regard, you might consider the SqlMembershipProvider that comes with .NET. It can be used with MVC and provides the means to get roles and the current security context, is easy to setup and configure and will be more secure than rolling your own.
If you are not using SQL Server, you have a couple of choices. One solution would be to use something like SQL Server Express or SQL Server Compact Edition to maintain the credentials. Another solution would be to mimic the SqlMembrershipProvider database schema and then write a custom provider that communicates with that schema.
The last choice would be to write a custom MembershipProvider class. While this is still rolling your own, it forces you into the structure of the MembershipProvider so that you can swap it out at a later date for a different one (e.g. ActiveDirectoryMembershipProvider) and provides a common interface for interacting with credentials and logins which for example enables easy use of the built-in Login control.
If you are already using a MembershipProvider and are asking about storing additional user-specific data, then I would suggest the SqlProfileProvider with all the caveats I mentioned above about the SqlMembershipProvider. the ProfileProvider provides a structure for maintain user-specific data with the currently logged on user.
For more information:
Introduction to Membership
Implementing a MembershipProvider
ASP.NET Profile Providers
You could also implement a custom identity. They are very easy to implement, and they let you store whatever user information you want in Identity, which is then stored in the cookies that Identity puts down, so you're not hitting the DB every time to get that info.
Just create a new class that inherits from GenericIdentity, and you'll be on your way.
You of course have to be careful how much info you put there since it's in a cookie, but usually user related information in the case you're talking about here isn't so big.
We use a custom identity to store a few bits of info about the user, and it works out pretty well.
You could store an object in session that holds all the required user information. You will just need to add a property in the Controllers, Views or other base classes where you want to retrieve the user information/profile. This would be the authorisation info as opposed to any authentication info (eg Forms authentication)
You might try "Windows Identity Foundation". I've been using it on one of my projects for a while. It allows for "claims-based authentication", which basically means that you get to designate "claims", strings of information that describe the user when she logs on.
Once logged on, the user's claims can be read from the HttpContext.Current.User field. You can also use "Role" claims that seamlessly integrate with a role-based authentication schema; meaning that you can give the user a "manager" role claim and then use `if (User.IsInRole("manager")).
As an added bonus, WIF makes it very easy to re-use your login screen in other applications.
All in all, it's very flexible, but the documentation is very poor. I've asked and answered a number of questions about "Windows Identity Foundation" on StackOverflow.
We have done this quite a few times in the past. Similar to what Thomas mentions, what we have generally done is implemented a new Membership provider based on the Microsoft SQL Memberhsip provider to do this. We inherit from the base MembershipUser class and add any custom properties we would want to have on the user object. You have to implement a database read for the Membership provider on the GetUser implementation, so you can consolidate your extra properties you need into that database read.
If you are using SQL server, Microsoft has release the 2.0 code for it. You can get more information at Scott Gu's blog.
http://weblogs.asp.net/scottgu/archive/2006/04/13/442772.aspx
If you want to start from scratch, they also have good resources at MSDN.
http://msdn.microsoft.com/en-us/library/f1kyba5e.aspx
and
http://msdn.microsoft.com/en-us/library/6tc47t75.aspx
Once you have implemented your provider, you can then add the Membership user to the Items collection of the current web context to get access to it from your code. The non extended properties from the base base user class are also available on the Request thread like normal.
With the Microsoft release of the 2.0 version of the source code , we found it helped us alleviate some concerns that exist about reinventing. Another thing to consider for your implementations is based on your scenario, you can bypass implementing some of the code. An example of this would be the CreateUser code if you are hitting a back end system that already has the credential information.
It seems like you're relatively happy with your authentication process but you want to explore other options for session/settings.
My suggestion has to do with settings only (roles, preferences, etc.)
In my opinion, having to traverse the whole technology stack from UI to Business Tier to DB tier to DB is sometimes a bit overkill.
For data that isn't likely to change during a session, this adds a lot of overhead... There are potentially several data transformations happening (DB (Relational Format) -> ORM -> Web Service XML Serialization -> Web Tier deserialization).
You might consider a session system that doesn't rely on a heavy RDBMS system or on the ASP.NET Caching / Session model. There are options that are very performant and that scale well.
You could use RavenDB by Ayende Rahien (Built for .NET). Its main goal is to provide low latency, high performance access to schema-less JSON documents.
Using this solution, you would set up ravenDB in the web tier so that access to data is very quick.
The first time you authenticate and retrieve settings, you would store the userID and settings information in this session DB.
Every time you load your controller after that, the settings data is accessible without having to go back to the RDBMS.
This DB could also be used to cache other web related data.
As for security, the settings data makes it to the web tier regardless of the method you use. This solution would be no more or less secure than the other options (more secure than an unencrypted cookie). If you needed to, you could encrypt the session data - but that will increase your overhead again.
Just another one of the million options to consider.
Good Luck,
Let us know what you decide!
Patrick.

Securing an ASP.Net MVC Site

As a relative newcomer to both web and MVC, I am looking for a good summary of security best practices that I should implement.
The site will be public facing with "moderately sensitive data" (meaning we can't get sued, but probably wouldn't make many friends if the data got out!) and will have the following security steps taken:
a: Forms/membership authentication and authorization
b: Parameterized queries to prevent sql injection.
c: Automatic timeout with x min of inactivity
c: SSL for client to server encryption
What else do you recommend?
*Securing IIS and the network don't fall under my domain, so I'm more interested in the things I need to do to the software.
If you are using cookies to recognize users, be sure to use an arbitrary token (such as a GUID) to store on the client for identification. I've seen too many websites that store my email address or username in my cookie... just have to change it to another!
Write your software so that it can run under medium trust.
If you are new to web development you should be aware of cross site scripting (XSS). You can use Http.Encode helper method to protect against this in ASP.NET MVC.
Make sure you prevent out of order requests. Ensure client is authenticated before allowing to see sensitive data, or in some cases, make sure the client has come through the correct channel, before allowing a data manipulation. For example, only allow adding an item to your cart if the request came from the product details page. If you don't check, any one can mess around with the action. The URL would be like http://server/cart/add/XYZ123 and anyone could just tweak the 'id' parameter.
Here's another biggie to watch out for: CSRF
http://blog.codeville.net/2008/09/01/prevent-cross-site-request-forgery-csrf-using-aspnet-mvcs-antiforgerytoken-helper/
Take a look at this post by Phil Haack- one of the MS dev’s involved in the development.
Additionally take a look at Microsoft Anti-Cross Site Scripting Library to filter out all incoming parameters
Maybe you should choose methods that can be invoke from outside or not. For example be careful make a method like delete any tables like http://yourhost.com/edit/deletealltable.
Make sure you design your class and methods well. And give attributes [NonAction] for preventing public method being invoke.
Make sure you display data (especially sensitive) as you need with minimum fancy design and use client script as long as needed.
Remove any unused trash files like unused files in your solution folder.
Check and double check and validate any input control like textbox. I just can give something in the textbox to hack your system.
If you use mix between MVC and regular ASP.NET, please remove any dependency between them.
Be sure you cover the basics thoroughly, independently of ASP.NET. Make sure your DBMS has a separate user with the minimal required privileges (e.g., CRUD and executing sprocs from specified databases) set up to access the database from the web application. Parameterizing queries is an excellent idea, but ALWAYS SCRUB YOUR INPUT ANYWAY: it is not a complete defense against sql injection.
Keep your design clean and easy to understand. Document whatever you do clearly, especially on the database side. It would be very bad if all your good work were destroyed by two programmers months or years later--one who didn't realize, say, that the database user for the web application (now accessing a database on a different server) shouldn't have root privileges, and another who added a control that didn't cleanse input properly. There's only so much that can be done about this sort of thing, but designing for the possibility that fools will be maintaining your code isn't so that coders will think you're sweet--it's so that fools won't put you out of business.

Resources