Golang: Crypto sign cookies for security

You can improve the security of your Go web application by cryptographically signing cookies using sugarcookie. A small library used to for signing cookie values that you can verify and trust on a user's return visit. This gives you strong trust and allows you to decouple the cookie from a session on a specific server.

The signed cookie consists of a a secret value, a timestamp, and a unique identifier; which is one-way hashed, then concatenated with the timestam and unique identifer. Then everything is base64 encoded making it suitable for storing in a cookie.


hash := sha256.Sum256([]byte(secret + strconv.FormatInt(t, 10) + uniqueUserId))
value := hex.EncodeToString(hash[:]) + "-" + strconv.FormatInt(t, 10) + "-" + uniqueUserId
signature := base64.StdEncoding.EncodeToString([]byte(value))

You verify the cookie is valid by replaying the hash with the secret and the supplied timestamp and unique ID.

Including the time as part of the hash means you can use it as a secondary mechanism to invalidate the cookie. If it's too old, maybe an half an hour, you know it's no longer good, no need to test it; just invalidate it.

Golang: Crypto sign cookies for security by  
  go  http  sessions  golang 
Like what you read? Share it:
  Facebook   Twitter   Google+