Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better ways to implement more secure Play Scala framework session via cookie

I really like the idea to keep session data on the users browser but don't like the fact that session cookies are not very secure in play framework. If someones steals the cookie, he/she could use it to permanently access the site since cookie signature is not expiring and cookie expiration doesn't help here because it doesn't stop from reusing the cookie if someone has stolen it.

I've added time stamp to expire the session after 1hr and every 5min to update the time stamp if user is still using the site so the cookie signature is rolling and expiring.

I am pretty new to scala and play framework so any suggestions or better ways to achieve the same would be much appreciated.

trait Secured {
  def withAuth(f: => String => Request[AnyContent] => Result) = {
    Security.Authenticated(username, onUnauthorized) { user =>
        Action(request => {

          val sessionRolloverPeriod = 300
          val sessionExpiryTime = 3600
          val sessionCreationTime: Int = request.session("ts").toInt
          val currentTime = System.currentTimeMillis() / 1000L

          if(currentTime <= (sessionCreationTime + sessionExpiryTime)) {
            if(currentTime >= (sessionCreationTime + sessionRolloverPeriod)) {
              f(user)(request).withSession(request.session + ("ts" -> (System.currentTimeMillis() / 1000L).toString))
            } else {
              f(user)(request)
            }
          } else {
            Results.Redirect(routes.Auth.login()).withNewSession
          }
        }
      )
    }
  }
}

Cookies produced every 5min:

The cookies produced every 5min: 
Cookie:PS="a6bdf9df798c24a8836c2b2222ec1ea4a4251f301-username=admin&ts=1381180064"
Cookie:PS="D7edg7df709b54B1537c2b9862dc2eaff40001c90-username=admin&ts=1381180380"
like image 414
Andriusa Avatar asked Oct 07 '13 21:10

Andriusa


1 Answers

Seems reasonable to me, I probably put it serverside though, give the client a "session-id" and delete the session when a user logs out. Doing it all client side means there is no way to invalidate the session if it has been stolen except to wait for the timeout.

like image 179
johanandren Avatar answered Nov 15 '22 05:11

johanandren