Storing sensitive data in HttpContext.Current - asp.net-mvc

ASP.NET MVC Web application where I am wanting to hold on some sensitive information (an account number) while the user navigates from page to page. I currently am using FormsAuthentication and storing it in a custom IPrinciple. I've encrypted the session cookie and set it to be HttpOnly (can't be accessed via client-script only). This seems like a good and secure solution to me.
However, I've been told we probably want zero sensitive information in a cookie for any reason. So an alternative I'm considering is storing the sensitive information in HttpContext.Current.Items. This would require the user to re-log in for each request but that's ok in this case. They should never come to the site directly, but through links from other sites (which posts authentication information, so the user never manually logs in).
Is there any reason not to use HttpContext.Current for this purpose?

Related

How to authenticate from a token in a URL?

I need to create a website with non standard authorizaion logic (or rather not exactly the site. It should be separate Area in existing ASP.NET MVC3 application). Access to most of the pages sould be available only to authorized users. Authorization is carried out on the token passed in the link. After the user arrived to this area, the token should be checked and if it’s valid site will create a session key for 30 minutes (we already have our own mechanisms of session managment and it should be used).
Workflow example :
Third-party website generates a link for user, e.g. https://example.com/securedPage/?accountId=123456&token=XXXXX
Our site check this token (it depends on the page from URL, in this case https://example.com/securedPage/)
If the token is valid, example.com obtains a session key for the user and stores it in cookies.
Then user continues browsing whole website and only session is checked.
I’m new to MVC framework, so I’d like to ask several questions about architecture.
What is an apropriate place for this logic? ActionInvoker, Global.asax etc.?
Currently I'm trying to create my own ActionInvoker and keep this logic there, but I'm afraid that it could be a wrong way.
If I understand correctly you want yo extend the Action of the controller to inject/check your token.
I think the global action filters should help you.

mvc site, most secure way to preserve login credentials

ok so, i have this dilemma on how i should save login credentials in mvc at the same time avoid as much hit on the database. i know i can easily use Forms Authentication to save a User instance but is it advisable?
At the moment the way I do it is I store the User Id in a cookie which i then would access everytime an Action gets called that would "require" a login access. Before the action gets accessed the User Id will be used to retrieve a "New" User instance. This will be the same on every Action, I don't store the User in the cookie as I feel like once the cookie is compromised everything about the User shall be available for the hacker (Userid, email, roles, etc)
So if i have a ton of actions that would require a login that will be difficult on my bandwidth. What do you think of the method I'm using? Should I change it to have all the User object be stored in the cookie with a short timeout? Any ideas are greatly appreciated.
thanks!!
It seems like you are trying to address a bandwidth issue. That alone would suggest that you shouldn't store more than you have to (ie: session id) in the cookie.
There are two major problems (among others) for using cookies.
1) They are sent up on every request
2) There is only limited amount of information you can store.
In general, trusting anything the user gives you (that includes encrypted cookies) is bad.
How many concurrent users do you foresee having on your website? Keep in mind that the database will be able to cache certain calls. Furthermore, if you are using a ORM like nhibernate, you will get 2nd level caching there. If all else fails, could you use the in-memory session management?
The biggest problem I have with putting userid's in the cookie is the entropy of that key. Say your userId is an email. All I have to do as an attacker is guess a userid that is valid in your system, and I will "automatically" become that user. The reason why people use sessionID's and then retrieve the user is that in theory sessionID's are harder to guess.
My suggestion would be to use database session management if you are in a load balanced situation. If not, use in-memory. It is fast. Memory is cheap. And unless you are storing 10's of mb of data in session for each user, and you have 10000's of users, you should be fine.
As Ken stated, you should probably be using the standard [authorize] tags available with MVC as opposed to creating your own method.
It sounds like you pretty much implemented form based authentication and something comparable to the [Authorize] attribute.
So if i have a ton of actions that would require a login that will be difficult on my bandwidth
Forms Authentication uses a cookie and is baked into the system. If you don't want to store your user information in SQLServer there are plenty of other options.
It sounds like you are trying to implement something that is already done. In my opinion, let's leave the security stuff to people that know about security. I would suggest working within the framework provided unless you have proof that you solution needs something else!
There is a UserData property on the FormsAuthenticationTicket object that could be used to store additional data other than the Username.
I had a project that had a similar need. I stored the values as a NameValueCollection encoded like a query string:
"email=myemail#some.com&roles=Somebody&roles=Special"
(there's also a handy HttpUtility.ParseQueryString() method that is useful for getting the values back out of the UserData property)
You can use the FormsAuthentication.Encrypt and FormsAuthentication.Decrypt to convert the ticket to and from the Cookie value.

When does the .NET FormAuthentication ticket get checked and how do I tap into this event?

We are attempting to integrate an ASP.NET MVC site with our client's SSO system using PingFederate. I would like to use the built in FormsAuthentication framework to do this. The way I've gone about it so far is:
Set up my Web.config so that my FormsAuthentication LoginURL goes to my site's "BeginAuthentication" action on a "Security" controller. From this action, I set up some session variables (what URL was being accessed, for example, since Ping won't send this info back to me), and then redirect to our client's login page on an external site (www.client.com/Login for example).
From here, the authentication takes place and a cookie is generated on the same domain as the one that our application is running on which contains the unique identifier of the authenticated user, I've set it up so that once this happens, the Ping server will redirect to my "EndAuthentication" action on my "Security" controller.
In this action, I call my membership class's "ValidateUser" method which takes this unique identifier from the cookie and loads in the user on our application that this ID refers to. I save that logged in user in our Session (Session["LoggedInAs"], for example) and expire the cookie that contains the id of the authenticated user that the SSO system provided for me.
All of this works well. The issue I'm wondering about is what happens after our user has already authenticated and manually goes back to our client's login page (www.client.com/login) and logs in as another user. If they do that, then the flow from #2 above to number 3 happens as normal - but since there already exists an authenticated user on our site, it seems as though the FormsAuthentication system doesn't bother kicking off anything so I don't get a chance to check for the cookie I'm looking for to login as this new user. What I'd like to do is, somewhere in my Global.asax file (probably FormsAuthenticate_OnAuthenticate), check to see if the cookie that the SSO system sends to me exists, and if so, sign out of the application using FormsAuthentication.SignOut().
Another issue that seems to be related is that if I let my Session expire, the FormsAuthentication still seems to think I am authenticated and it lets me access a page even though no currently logged in user exists in my Session, so the page doesn't render correctly. Should I tap into the Session_End event and do FormsAuthentication.SignOut() here as well?
Basically, I want to know when the authentication ticket created by
System.Web.Security.FormsAuthentication.SetAuthCookie(..) gets checked in the flow of a request so that I can determine whether I need to SignOut() and force revalidation or not.
Thanks for any help. Sorry for the length of this message, trying to be as detailed as possible.
Mustafa
Welcome to the small section of Hades that is mixing session with formsauth.
If your needs are as complex as presented, you would get more sleep if you implement a full provider stack to share amongst the participating sites. Easier said than done, I know.
But to address your question:
from http://www.codeproject.com/Articles/39026/Exploring-Web-config-system-web-httpModules.aspx
On the way in....Check ticket and set identity #
app.AuthenticateRequest += System.Web.Security.FormsAuthenticationModule.OnEnter-->OnAuthenticate
On the way out... set the ticket and redirect as necessary
app.EndRequest += System.Web.Security.FormsAuthenticationModule.OnLeave
Reflector is your friend. ;-)
I don't know about a specific event for when the cookie is checked, but you could place the appropriate logic in Application_BeginRequest() and check the user's authentication state there.
Another issue that seems to be related
is that if I let my Session expire,
the FormsAuthentication still seems to
think I am authenticated and it lets
me access a page even though no
currently logged in user exists in my
Session, so the page doesn't render
correctly.
The life of the cookie (how long until ASP.NET feels it needs to ask for a password again) and how you are managing state are unrelated. The ASP.NET authentication is cookie based so that, should a developer want to, he could turn off viewstate, session, use no query strings or hidden fields and authentication still works.
If you want to tie the interval at which you request the password to how you are persisting data, then you will want your session expiration to be roughly the same as the cookie expiration, but they will never quite match up. It would be better to have two policies (one for how fast you throw away a users session data and one for how long you are willing to wait before you need to reask for a password)

Session vs Cookie vs Custom IPrincipal

I'm working on a project where certain logged in users have a dedicated page which they can choose the url of. When a user logins in i would like to display a link "View my page". I was just wondering what is the best way to store this baring in mind it needs to be accessible for as long as the user is logged in (The site has a remember me feature as well). Would a session variable surfice? or a cookie? Or a custom IPrincipal?
Many thanks
Matt
UPDATE:
What do you guys thing of using the UserData string you can store with the authentication cookie? It seems to satisfy my requirements, but i can't say I know a lot about it.
Forms authentication (based on cookie) should be enough. Here you can read about using FormsAuthentication with custom IPrincipal:
ASP.NET 2.0 Forms authentication - Keeping it customized yet simple
This page is about how forms authentication works:
Explained: Forms Authentication in ASP.NET 2.0
When you use forms authentication, you have Authorize attribute to limit access to controllers and action. It works pretty well. Your own IPrincipal is not necessary. I wouldn't use Session, because it can be easily lost.
Thanks guys, however I have ended up using the UserData string that you can store along with the authentication cookie. This way I know the data will always be available while the user is authenticated. And since I only need to remember simple data (the users url), this seems like a good solution.
Anybody with the same problem can find more info here:
http://www.asp.net/learn/security/tutorial-03-cs.aspx (See step 4)
If what you mean is that you want to display a different custom URL for each user and you simply want to cache that URL then there's a few things to consider:
If you use a session value or a cookie then you need code for the possibility of the value not being present. Both the server session or the browser session could expire and the user could still be logged in.
If you use a cookie you could consider setting the cookie expiry to the same as the authentication cookie expiry but this still doesn't guarantee availability.
A cookie value will not be secure, it could be modified. A session value will be secure.
If you're using custom forms authentication then you could store the URL in the authentication cookie itself and then load it into a custom IPrincipal. I would advise against that as I don't feel it's the right place.
If you're just trying to cache the URL then as long as your code re-fetches the data when the value is not present then a session value or a cookie will be fine depending on the level of security required.
If I have read that wrong and you just want to show/hide a link to depending on whether a user is authorized or not you can simple use
<% if (User.Identity.IsAuthenticated) { %>
view my page
<% } %>
And have your MyPage action in your controller render the dedicated page for the user.

Caching account information

I currently using my own membership implementation on a ASP.MVC project. I've got an Account and an Account can have more than 1 memberships.
I am not sure what is the best approach to follow with Account information being cached. I am currently loading the account information for almost each request from the User property of the controller.
Should I cache the account information? And if where would be the best place, cookies or Session?
I recommend fairly strongly against sessions. They won't scale well and do not fit into web/HTTP type of architectures. See 'Key REST principles' in this REST article if you like the REST stuff.
I would suggest to put the user information in cookies (don't over do it, just really required stuff).
And keep sensitive information in the ASP.NET Forms authentication cookie. See Forms Authentication article, "Step 4: Storing Additional User Data in the Ticket".
Fetch the rest of the data from the database. Avoid premature optimization.
As is often the case with these questions, the answer is "it depends".
Cookies are fine if you are only storing small amounts of string data. There are limitations (4k per cookie, HTTP header limit) and they are sent across the wire with every request and response. You might have to "re-inflate" your account/member info from data stored in the cookie. Users can opt to not accept cookies from your website.
Session is strongly-typed (no re-inflation) and not transmitted with every request/response. There are several options for scaling up session storage if you think your web app will need it. Most small-medium sites use session with no problems.

Resources