Play Framework (10) – Cookie by Scala

Last time, we use cookie/session to help us to enhance web application’s security issue. This time, we talk about how to design normal cookie and use it to improve user experience. Our target is to avoid user’s trouble to login many times. User only needs to login once and come back in future without login. Cookie is also used to recognize user and obtain user information without boring user.

  1. Cookie Design

    1. Cookie is constructed by user name, ip, expired time and salt. Here I use constant string to combine them.
      Cookie = Encode(userName + IP + ExpiredTime + Salt)
    2. import scala.util.Random
      def createCookieString(userName: String, request: Request[Any]): String = {
       val expireTime = createExpireTime(<your_cookie_maxAge>)
       val ip = request.remoteAddress
       val salt = Random.alphanumeric.take(5).mkString
      
       val valueString = Seq(userName, ip, expireTime, salt).mkString(<your_constant_string>)
       val valueEncodedString = DAOBase64.encode(valueString)
       valueEncodedString
      }
    3. Create expired time
    4. def createExpireTime(maxAge: Int): String = {
        val now = new DateTime()
        val expireTime = now.plusDays(maxAge)
        expireTime.toString()
      }
    5. Cookie must be encoded, here is encode code
    6. import org.apache.commons.codec.binary.{ Base64 => ApacheBase64 }
      object DAOBase64 {
       def decode(encoded: String) = new String(ApacheBase64.decodeBase64(encoded.getBytes))
       def encode(decoded: String) = new String(ApacheBase64.encodeBase64(decoded.getBytes))
      }
    7. Parse your cookie
    8. def parseCookieString(input: String): CookieMessage = {
        val decodeCookie = DAOBase64.decode(input)
      
        val cookieStrings= decodeCookie.split(<your_constant_string>)
        val userName = cookieStrings(0)
        val ip = cookieStrings(1)
        val expireTime = cookieStrings(2)
      
        CookieMessage(input, userName, ip, expireTime)
      }
    9. case class CookieMessage(cookie: String, userName: String, ip: String, expireTime: String)
  2.  Return Cookie

    1. def buildCookie(cookieString: String): Cookie = {
        Cookie(Shared.cookieName, cookieString, maxAge = Some(<your_cookie_maxSec>))
      }
      Ok(userInfoTemp)
        .withSession("WWW-Authenticate" -> "user")
        .withCookies(buildCookie(cookieString))
  3. Clean up Cookie

    1. Ok.withNewSession
        .discardingCookies(DiscardingCookie(Shared.cookieName))
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s