Rails 5 session.delete, not deleting cookies in my browser - ruby-on-rails

I've been doing the exercise in
https://www.railstutorial.org/book/basic_login#sec-exercises_logging_out
It's says that I should confirm that the session is deleted after logging out,
Does deleting the session using
session.delete(:user_id)
will make the cookie in my browser (Firefox), disappear?
Also, I've noticed that the content of the cookie changes when I'm visiting different pages in my website, is that an intended behavior? I also get cookies when visiting my website, for the first time, even when not logging on

No, it will simply remove the key from the cookie as we can see in the source code https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/request/session.rb#L146.
It will in effect kill the authenticated but the cookie will still be there (it just won't say the user is authenticated anymore).
Also, I've noticed that the content of the cookie changes when I'm visiting different pages in my website, is that an intended behavior?
Yes, if you're using CookieStore (which is the default way in Rails) all the data is stored on the cookie. So if you add or change fields, the cookie changes . (You will notice that the data is encrypted so this is secure). http://api.rubyonrails.org/classes/ActionDispatch/Session/CookieStore.html
I also get cookies when visiting my website, for the first time, even
when not logging on
It makes sense that Rails starts the session even before any authentication is happening - it's basically just an identifier without any data any it yet. A "Session" doesn't have to mean an authenticated user, you might want to save the user's preferred language or the time he opened the website even before he's authenticated.

Related

Rails 4 session variable without a cookie

Because of the awesome EU directive on allowing users opt out from having cookies stored I have the following problem.
I have a message that displays at the top of the screen that asks the user to opt in or opt out.
if the user opts in, cookies are turned on using rack.policy, and the message is hidden. A cookie variable is set to say that the message should not be shown again for future visits. Perfect
If the user opts out. Cookies are disabled, fine. the message is cleared.... and a session variable is set to say don't show the message for this session. This would be fine, but it seems the session variable is saved in the same way as a cookie and the rack policy does not allow it to be displayed. The message therefore flashes up on every single page.
So first, thank you EU. Second, how do I save a "session variable" without saving to a cookie?
Unless you try going for something more exotic like local storage offered by the browser, you can't. The rails guide explicitly states:
All session stores use a cookie to store a unique ID for each session (you must use a cookie, Rails will not allow you to pass the session ID in the URL as this is less secure).
I'm no lawyer, but for what it's worth I believe that law is intended to apply to cookies used for marketing/tracking purposes and does not apply to cookies needed for the site to function like cookies used for authentication or ephemeral storage. With this in mind, you could use the rails's session cookie for must-have data and use separate cookies for other purposes that your application can disable.
I wouldn't take it as gospel, but this Wired article seems to a good job of providing a simplified explanation.

ActiveDirectoryMembershipProvider and Forms authentication

I've got a ASP.NET MVC web app which uses forms authentication.
I'm using ActiveDirectoryMembershipProvider to validate users against our domain.
if (Membership.ValidateUser(m.Username, m.Password))
{
FormsAuthentication.SetAuthCookie(m.Username, true);
....
This means the user gets validated only when they log in.
Problem with that is ofcourse that if the user's password changes they still remain logged in. Or worse, user leaves our company with a grudge, and they still have access.
I would have thought such a simple use case would have an obvious answer but I've been stuck on this for a while now.
I could put the users password in the session and then validate it every time, but that doesn't feel right.
What is the suggested/correct way of handling this?
The typical solution is to force log out when users unsubscribes from the service or less commonly when they change password. Use this method:
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
If the user can be deactivated outside of the app (i.e. Active Directory), the typical practice is to rely on the session time-out and perhaps ask for the credentials once more for critical operations. If you absolutely cannot allow the deactivated user to work while the session is still active, then yes, you'll have to check the credentials on every request. Since storing the password in the app is a very bad idea, it means you'll have to ask for credentials on each request which arguably is an even worse idea.
As for the password change, it normally doesn't modify the user's permissions so it should be harmless to allow for them to continue working.
The answer is to periodically (every 30 minutes or so) check User.IsApproved and User.LastPasswordChangedDate to make sure the users credentials are still valid.
To do this you need to manually create the FormsAuthenticationTicket and cookie, rather than using FormsAuthentication.SetAuthCookie.
Put the date you validated the user inside UserData and compare this against LastPasswordChangedDate.
I've implemented this and it works perfectly.
More information here
Check if Active Directory password is different from cookie

Session not completely abandoned

I'm having an odd problem with my sessions. I haven't found a solution even after searching through the internet for a couple of days and I find it really strange that nobody else seems to be having this problem, which makes me think that it could be something I'm doing wrong.
If I log onto my website and visit a page decorated with the [Authorize] attribute (i.e. it requires the user to have logged on in order to access it), save the request with fiddler, log out and re-issue the request with fiddler one would expect that to fail (or re-direct me to the login page at least) but no, it returns the page as if I were still logged in.
When I'm logging out this is what I do (I'm using asp.net forms authentication)
FormsAuthentication.SignOut();
Session.Clear();
Session.Abandon();
Session.RemoveAll();
Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId",""));
That should work... but it doesn't.
In case anyone is wondering this is what I am using:
IIS 7.5
MVC 3.0
.NET 4.0
If I log onto my website and visit a page decorated with the [Authorize] attribute (i.e.
it requires the user to have logged on in order to access it), save
the request with fiddler, log out and re-issue the request with
fiddler one would expect that to fail
Why would you expect something like this? Forms authentication uses cookies to track logged in users. When you do FormsAuthentication.SignOut(); all that happens is that you remove the authentication cookie so that on subsequent requests from this browser the cookie is no longer sent and the server thinks that the user is not logged in. If on the other hand you have captured a valid cookie with Fiddler, you are perfectly capable of sending a valid request to the server (in the time for which this cookie is valid obviously). There is nothing on the server for it to know that you used fiddler, right? It's completely stateless.
If you wanted to avoid this behavior (which is by design) you will have to keep track somewhere on the server either a list of online users, or add some flag in the database about the user which indicates whether he is online or not. Then you will write a custom Authorize attribute that will check in this centralized store whether the user is allowed or not to login. When he logs out you will change this flag. Obviously if he closes his browser you won't be able to change the flag but if he signs out normally you will know that even if someone had captured the authentication cookie, he will not be able to use it to issue a valid request.

Copying cookies from main domain to subdomain

My application has a userspace which used to be accessed by a url like domain.com/~username, but I am in the process of converting that to using subdomains instead (username.domain.com). However, I am running into an issue that I'm hoping someone might have an idea of how to get around.
Currently, visitors to a user's site get a cookie of the form user<id>_authentication (where <id> is the user ID of the site they're visiting), which is set to have the domain www.domain.com. However, now that I'm switching to subdomains, I want to find those cookies and transfer them to a new cookie called authentication per subdomain, using the subdomain as the cookie domain. However, the rails cookies array does not find the main domain cookies.
I know that if the old cookies were using .domain.com as the domain instead, they'd apply to the subdomain and would be present in cookies, but these cookies are already existing, and I'm trying to make the change as seamless for a user as possible -- so if they had an authentication cookie already for a site, I want them to not have to reauthenticate if at all possible.
Is there any way I can get the cookies from the main domain or does anyone have another suggestion of how I can transfer the cookies?
Update: Sorry, I didn't make it clear before, the cookie is only set if the visitor actively authenticates themselves by submitting a form on the user's site.
If you change the cookie domain to be more permissive (applying to more sub domains) you have no way to read the old, more restricted cookies except from the top level domain that used to work.
You will have to read the cookie, authenticate, and then write a new more permissive cookie before the cookie can be read by the subdomain.
You can roll out your migration logic in advance of the feature and hope you get most people. The rest will have to re-authenticate manually.
Personally I think they should have to re-authenticate.. it will only happen once, then they'll have the new ".domain.com" cookie.
But... One way to achieve this would be to check for the new cookie and when failing to find it, redirect to a new page on the main domain, providing the return url.
In that new page, check for the old style cookie, set the new style cookie, and redirect to the original url. if they don't have the old style cookie, redirect to the login area.
hope this helps.

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)

Resources