Title: aah Cookie Manager Desc: aah provides a secure cookie manager Keywords: secure cookie manager, cookie manager, cookie
aah provides a secure cookie manager to fulfill custom secure cookie purpose. It does AES encryption and HMAC SHA signing.
import "aahframe.work/security/cookie"
A sample code snippet to create a secure cookie manager is below. For non-secure cookie manager, simply supply signKey
.
import ess "aahframe.work/essentials"
// Create cookie options
opts := &cookie.Options{
Name: "mycustomcookie",
Domain; "aahframework.org",
Path: "/",
MaxAge: 2629746, // 1 month in seconds
HTTPOnly: true,
Secure: true, // use only SSL enabled website
}
// Get sign and encryption keys from configuration
cfg := aah.App().Config()
signKey := cfg.StringDefault("myapp.mysecure.cookie.key.sign", ess.SecureRandomString(32))
encKey := cfg.StringDefault("myapp.mysecure.cookie.key.enc", ess.SecureRandomString(64))
// Creating a secure cookie manager
cookieMgr := cookie.NewManager(opts, signKey, encKey)
Using secure cookie manager, manipulating cookie value is like a breeze.
// create and reply
httpCookie := cookieMgr.New("This is my secure cookie value")
c.Reply().Cookie(httpCookie)
func (c *ProductController) Show(id string) {
cookieValue := c.Req.Cookie("cookiename")
b, err := cookieMgr.Decode(cookieValue)
if err != nil {
// invalid cookie
c.Session().SetFlash("cookie.error", "Invalid cookie")
c.Reply().BadRequest().HTMLf("/errors/cookie.html", nil)
return
}
value := string(b)
c.Log().Info("Cookie value: ", value)
}