mirror of
https://github.com/kataras/iris.git
synced 2025-12-23 12:57:05 +00:00
enhanced cookie security and management
Former-commit-id: a97b0b33e87749a2e8c32e63269fcc60fa326ff3
This commit is contained in:
@@ -21,6 +21,8 @@ func init() {
|
||||
type Sessions struct {
|
||||
config Config
|
||||
provider *provider
|
||||
|
||||
handlerCookieOpts []context.CookieOption // see `Handler`.
|
||||
}
|
||||
|
||||
// New returns a new fast, feature-rich sessions manager
|
||||
@@ -38,52 +40,46 @@ func (s *Sessions) UseDatabase(db Database) {
|
||||
s.provider.RegisterDatabase(db)
|
||||
}
|
||||
|
||||
// GetCookieOptions returns any cookie options registered for the `Handler` method.
|
||||
func (s *Sessions) GetCookieOptions() []context.CookieOption {
|
||||
return s.handlerCookieOpts
|
||||
}
|
||||
|
||||
// updateCookie gains the ability of updating the session browser cookie to any method which wants to update it
|
||||
func (s *Sessions) updateCookie(ctx context.Context, sid string, expires time.Duration, options ...context.CookieOption) {
|
||||
cookie := &http.Cookie{}
|
||||
|
||||
// The RFC makes no mention of encoding url value, so here I think to encode both sessionid key and the value using the safe(to put and to use as cookie) url-encoding
|
||||
cookie.Name = s.config.Cookie
|
||||
|
||||
cookie.Value = sid
|
||||
cookie.Path = "/"
|
||||
cookie.Domain = formatCookieDomain(ctx, s.config.DisableSubdomainPersistence)
|
||||
cookie.HttpOnly = true
|
||||
if !s.config.DisableSubdomainPersistence {
|
||||
cookie.SameSite = http.SameSiteLaxMode // allow subdomain sharing.
|
||||
}
|
||||
|
||||
// MaxAge=0 means no 'Max-Age' attribute specified.
|
||||
// MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
|
||||
// MaxAge>0 means Max-Age attribute present and given in seconds
|
||||
if expires >= 0 {
|
||||
if expires == 0 { // unlimited life
|
||||
cookie.Expires = CookieExpireUnlimited
|
||||
cookie.Expires = context.CookieExpireUnlimited
|
||||
} else { // > 0
|
||||
cookie.Expires = time.Now().Add(expires)
|
||||
}
|
||||
cookie.MaxAge = int(time.Until(cookie.Expires).Seconds())
|
||||
}
|
||||
|
||||
// set the cookie to secure if this is a tls wrapped request
|
||||
// and the configuration allows it.
|
||||
if ctx.Request().TLS != nil && s.config.CookieSecureTLS {
|
||||
cookie.Secure = true
|
||||
}
|
||||
|
||||
// encode the session id cookie client value right before send it.
|
||||
cookie.Value = s.encodeCookieValue(cookie.Value)
|
||||
|
||||
for _, opt := range options {
|
||||
opt(cookie)
|
||||
}
|
||||
|
||||
AddCookie(ctx, cookie, s.config.AllowReclaim)
|
||||
ctx.UpsertCookie(cookie, options...)
|
||||
}
|
||||
|
||||
// Start creates or retrieves an existing session for the particular request.
|
||||
// Note that `Start` method will not respect configuration's `AllowReclaim`, `DisableSubdomainPersistence`, `CookieSecureTLS`,
|
||||
// and `Encoding` settings.
|
||||
// Register sessions as a middleware through the `Handler` method instead,
|
||||
// which provides automatic resolution of a *sessions.Session input argument
|
||||
// on MVC and APIContainer as well.
|
||||
//
|
||||
// NOTE: Use `app.Use(sess.Handler())` instead, avoid using `Start` manually.
|
||||
func (s *Sessions) Start(ctx context.Context, cookieOptions ...context.CookieOption) *Session {
|
||||
cookieValue := s.decodeCookieValue(GetCookie(ctx, s.config.Cookie))
|
||||
cookieValue := ctx.GetCookie(s.config.Cookie, cookieOptions...)
|
||||
|
||||
if cookieValue == "" { // cookie doesn't exist, let's generate a session and set a cookie.
|
||||
sid := s.config.SessionIDGenerator(ctx)
|
||||
@@ -99,13 +95,34 @@ func (s *Sessions) Start(ctx context.Context, cookieOptions ...context.CookieOpt
|
||||
return s.provider.Read(s, cookieValue, s.config.Expires)
|
||||
}
|
||||
|
||||
const contextSessionKey = "iris.session"
|
||||
const sessionContextKey = "iris.session"
|
||||
|
||||
// Handler returns a sessions middleware to register on application routes.
|
||||
// To return the request's Session call the `Get(ctx)` package-level function.
|
||||
//
|
||||
// Call `Handler()` once per sessions manager.
|
||||
func (s *Sessions) Handler(cookieOptions ...context.CookieOption) context.Handler {
|
||||
s.handlerCookieOpts = cookieOptions
|
||||
|
||||
return func(ctx context.Context) {
|
||||
session := s.Start(ctx, cookieOptions...)
|
||||
ctx.Values().Set(contextSessionKey, session)
|
||||
var requestOptions []context.CookieOption
|
||||
if s.config.AllowReclaim {
|
||||
requestOptions = append(requestOptions, context.CookieAllowReclaim(ctx, s.config.Cookie))
|
||||
}
|
||||
if !s.config.DisableSubdomainPersistence {
|
||||
requestOptions = append(requestOptions, context.CookieAllowSubdomains(ctx, s.config.Cookie))
|
||||
}
|
||||
if s.config.CookieSecureTLS {
|
||||
requestOptions = append(requestOptions, context.CookieSecure(ctx))
|
||||
}
|
||||
if s.config.Encoding != nil {
|
||||
requestOptions = append(requestOptions, context.CookieEncoding(s.config.Encoding, s.config.Cookie))
|
||||
}
|
||||
ctx.AddCookieOptions(requestOptions...) // request life-cycle options.
|
||||
|
||||
session := s.Start(ctx, cookieOptions...) // this cookie's end-developer's custom options.
|
||||
|
||||
ctx.Values().Set(sessionContextKey, session)
|
||||
ctx.Next()
|
||||
}
|
||||
}
|
||||
@@ -116,14 +133,17 @@ func (s *Sessions) Handler(cookieOptions ...context.CookieOption) context.Handle
|
||||
// The `Sessions.Start` should be called previously,
|
||||
// e.g. register the `Sessions.Handler` as middleware.
|
||||
// Then call `Get` package-level function as many times as you want.
|
||||
// The `Sessions.Start` can be called more than one time in the same request life cycle as well.
|
||||
// Note: It will return nil if the session got destroyed by the same request.
|
||||
// If you need to destroy and start a new session in the same request you need to call
|
||||
// sessions manager's `Start` method after Destroy.
|
||||
func Get(ctx context.Context) *Session {
|
||||
if v := ctx.Values().Get(contextSessionKey); v != nil {
|
||||
if v := ctx.Values().Get(sessionContextKey); v != nil {
|
||||
if sess, ok := v.(*Session); ok {
|
||||
return sess
|
||||
}
|
||||
}
|
||||
|
||||
// ctx.Application().Logger().Debugf("Sessions: Get: no session found, prior Destroy(ctx) calls in the same request should follow with a Start(ctx) call too")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -144,7 +164,7 @@ func (s *Sessions) ShiftExpiration(ctx context.Context, cookieOptions ...context
|
||||
// It will return `ErrNotFound` when trying to update expiration on a non-existence or not valid session entry.
|
||||
// It will return `ErrNotImplemented` if a database is used and it does not support this feature, yet.
|
||||
func (s *Sessions) UpdateExpiration(ctx context.Context, expires time.Duration, cookieOptions ...context.CookieOption) error {
|
||||
cookieValue := s.decodeCookieValue(GetCookie(ctx, s.config.Cookie))
|
||||
cookieValue := ctx.GetCookie(s.config.Cookie)
|
||||
if cookieValue == "" {
|
||||
return ErrNotFound
|
||||
}
|
||||
@@ -172,17 +192,20 @@ func (s *Sessions) OnDestroy(listeners ...DestroyListener) {
|
||||
}
|
||||
}
|
||||
|
||||
// Destroy remove the session data and remove the associated cookie.
|
||||
// Destroy removes the session data, the associated cookie
|
||||
// and the Context's session value.
|
||||
// Next calls of `sessions.Get` will occur to a nil Session,
|
||||
// use `Sessions#Start` method for renewal
|
||||
// or use the Session's Destroy method which does keep the session entry with its values cleared.
|
||||
func (s *Sessions) Destroy(ctx context.Context) {
|
||||
cookieValue := GetCookie(ctx, s.config.Cookie)
|
||||
// decode the client's cookie value in order to find the server's session id
|
||||
// to destroy the session data.
|
||||
cookieValue = s.decodeCookieValue(cookieValue)
|
||||
cookieValue := ctx.GetCookie(s.config.Cookie)
|
||||
if cookieValue == "" { // nothing to destroy
|
||||
return
|
||||
}
|
||||
RemoveCookie(ctx, s.config)
|
||||
|
||||
ctx.Values().Remove(sessionContextKey)
|
||||
|
||||
ctx.RemoveCookie(s.config.Cookie)
|
||||
s.provider.Destroy(cookieValue)
|
||||
}
|
||||
|
||||
@@ -204,35 +227,3 @@ func (s *Sessions) DestroyByID(sid string) {
|
||||
func (s *Sessions) DestroyAll() {
|
||||
s.provider.DestroyAll()
|
||||
}
|
||||
|
||||
// let's keep these funcs simple, we can do it with two lines but we may add more things in the future.
|
||||
func (s *Sessions) decodeCookieValue(cookieValue string) string {
|
||||
if cookieValue == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
if decode := s.config.Decode; decode != nil {
|
||||
var cookieValueDecoded string
|
||||
err := decode(s.config.Cookie, cookieValue, &cookieValueDecoded)
|
||||
if err == nil {
|
||||
cookieValue = cookieValueDecoded
|
||||
} else {
|
||||
cookieValue = ""
|
||||
}
|
||||
}
|
||||
|
||||
return cookieValue
|
||||
}
|
||||
|
||||
func (s *Sessions) encodeCookieValue(cookieValue string) string {
|
||||
if encode := s.config.Encode; encode != nil {
|
||||
newVal, err := encode(s.config.Cookie, cookieValue)
|
||||
if err == nil {
|
||||
cookieValue = newVal
|
||||
} else {
|
||||
cookieValue = ""
|
||||
}
|
||||
}
|
||||
|
||||
return cookieValue
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user