Straightforward HTTP session management

sessionup 🚀

GoDoc Build status Test coverage Go Report Card

Simple, yet effective HTTP session management and identification package

Features

  • Effortless session management:
    • Initialization.
    • Request authentication.
    • Retrieval of all sessions.
    • Revokation of the current session.
    • Revokation of all other sessions.
    • Revokation of all sessions.
  • Optionally identifiable sessions (IP address, OS, browser).
  • Authentication via middleware.
  • Fully customizable, but with sane defaults.
  • Lightweight.
  • Straightforward API.
  • Allows custom session stores.

Installation

go get github.com/swithek/sessionup

Usage

The first thing you will need, in order to start creating and validating your sessions, is a Manager:

store := memstore.New(time.Minute * 5)
manager := sessionup.NewManager(store)

Out-of-the-box sessionup's Manager instance comes with recommended OWASP configuration options already set, but if you feel the need to customize the behaviour and the cookie values the Manager will use, you can easily provide your own options:

manager := sessionup.NewManager(store, sessionup.Secure(false), sessionup.ExpiresIn(time.Hour * 24))

During registration, login or whenever you want to create a fresh session, you have to call the Init method and provide a key by which the sessions will be grouped during revokation and retrieval. The key can be anything that defines the owner of the session well: ID, email, username, etc.

func login(w http.ResponseWriter, r *http.Request) {
      userID := ...
      if err := manager.Init(w, r, userID); err != nil {
            // handle error
      }
      // success
}

You can store additional information with your session as well.

func login(w http.ResponseWriter, r *http.Request) {
      userID := ...
      err := manager.Init(w, r, userID, sessionup.MetaEntry("permission", "write"), sessionup.MetaEntry("age", "111"))
      if err != nil {
            // handle error
      }
      // success
}

Public / Auth middlewares check whether the request has a cookie with a valid session ID and add the session to the request's context. Public, contrary to Auth, does not call the Manager's rejection function (also customizable), thus allowing the wrapped handler to execute successfully.

http.Handle("/", manager.Public(publicHandler))
http.Handle("/private", manager.Auth(privateHandler))

There's a FetchAll method, should you want to retrieve all sessions under the same key as the current context session:

func retrieveAll(w http.ResponseWriter, r *http.Request) {
      sessions, err := manager.FetchAll(r.Context())
      if err != nil {
            // handle error
      }
      // success
}

When the time comes for session termination, use Revoke method:

func logout(w http.ResponseWriter, r *http.Request) {	
      if err := manager.Revoke(r.Context(), w); err != nil {
            // handle error
      }
      // success
}

What if you want to revoke all sessions under the same key as the current context session? Use RevokeAll:

func revokeAll(w http.ResponseWriter, r *http.Request) {
      if err := manager.RevokeAll(r.Context(), w); err != nil {
            // handle error
      }
      // success
}

... and if you want to revoke all sessions under the same key as the current context session excluding the current context session, use RevokeOther:

func revokeOther(w http.ResponseWriter, r *http.Request) {
      if err := manager.RevokeOther(r.Context()); err != nil {
            // handle error
      }
      // success
}

Sessions & Cookies

On each Init method call, a new random session ID will be generated. Since only the generated ID and no sensitive data is being stored in the cookie, there is no need to encrypt anything. If you think that the generation functionality lacks randomness or has other issues, pass your custom ID generation function as an option when creating a new Manager.

Store implementations

Custom stores need to implement the Store interface to be used by the Manager.

Limitations

sessionup offers server-only session storing and management, since the functionality to revoke/retrieve session not in the incoming request is not possible with cookie stores.

Demo

You can see sessionup in action by trying out the demo in cmd/example/

Owner
I enjoy tinkering with computers and pondering why life is the way it is.
null
Comments
  • Redirect on private url

    Redirect on private url

    Hello

    On start thank you for your lib :)

    I create Session manager instance with code:

    var sessionManager = sessionup.NewManager(store,
    	sessionup.Secure(false),
    	sessionup.ExpiresIn(time.Hour*24),
    	sessionup.Reject(handler.Reject),
    )
    

    I have a little problem, I have free handlers:

    • google/login - public
    • google/callback - public
    • / - Auth

    In callback I have something like:

    if err := manager.Init(w, r, user.GoogleID); err != nil {
    			logger.Error(err)
                http.Redirect(w, r, handlerPathPrefix+"login", http.StatusPermanentRedirect)
    		} else {
                http.Redirect(w, r, "/", http.StatusPermanentRedirect)
            }
    

    When I'm redirected to / next Im redirected to google/login as if I didn't have a session. When I open / after it I have access of course.

  • Add additional expiration time check

    Add additional expiration time check

    Even though session stores should delete expired sessions or not return them from the Fetch methods, the expiration time should also be checked before performing other operations (e.g. in Manager.Auth()).

  • Update README with link to Bolt store implementation

    Update README with link to Bolt store implementation

    Hello!

    I've written a Bolt store implementation of sessionup. I'd like to ask you to add it to the README so other people could see and use it, if that's okay :).

    Thanks.

  • Fix session IsValid method to check for nil user agent

    Fix session IsValid method to check for nil user agent

    This fixes an issue where if we're trying to compare requests' empty User-Agent header with session that had one, it would cause a panic. This happens as empty User-Agent isn't parsed and returns nil user agent object, on which we're trying to access it's attributes.

  • Add link to SQLite store implementation to README

    Add link to SQLite store implementation to README

    Hello.

    I've written another SQLite store implementation for this package, it's a little bit different from the other one in terms that I tried to keep it more concise. It is also designed in a way that it's very similar to Bolt store package and both of them are trying to follow Uber Go guidelines.

    Thanks.

  • Add metadata field to session type

    Add metadata field to session type

    Add a new field of map[string]interface{} type to session.

    manager.Init() should also accept data (through variadic arguments) that would be stored in this field.

  • Detect changes of properties associated with the session

    Detect changes of properties associated with the session

    Include an option that allows sessionup to check for IP address / User-Agent data changes and, if needed, terminate the session. More information here.

  • Upgrade to v2

    Upgrade to v2

    • [ ] Rename:
      • [ ] Manager.Defaults() -> Manager.reset() (?)
      • [ ] Manager.Auth() -> Manager.Authenticate()/Manager.Private() (?)
      • [ ] Manager.Init(...) -> Manager.Create(...) Session (?)
      • [ ] Manager.Revoke() -> Manager.RevokeCurrent()
      • [ ] Manager.RevokeByIDExt() -> Manager.RevokeByID() (the old RevokeByID should be removed)
      • [ ] Manager.RevokeOther() -> Manager.RevokeAllOther()
      • [ ] DefaultReject() -> DefaultRejectHandler()
      • [ ] Reject() -> RejectHandler()
      • [ ] Session.UserKey -> Session.SharedKey (?)
    • [ ] Add Manager.OnRevocation(fn)
    • [ ] Create a new (optional?) store interface that would store past logins. This would allow the manager to check when the user sends a request from a new machine.
    • [ ] Use https://github.com/mileusna/useragent for user agent extraction.
    • [ ] Use the new netip.Addr type.
    • [ ] Use only RemoteAddr when extracting an IP address. To extract it from other places, the user should use other middlewares (like the one chi has).
Go session management for web servers (including support for Google App Engine - GAE).

Session The Go standard library includes a nice http server, but unfortunately it lacks a very basic and important feature: HTTP session management. T

Oct 10, 2022
Go (lang) HTTP session authentication

Go Session Authentication See git tags/releases for information about potentially breaking change. This package uses the Gorilla web toolkit's session

Dec 22, 2022
Validate Django auth session in Golang

GoDjangoSession Valid for django 3.0.5 Usage: package main import ( "encoding/base64" "fmt" "session/auth" "github.com/Kuzyashin/GoDjangoSession"

Aug 23, 2022
Package gorilla/sessions provides cookie and filesystem sessions and infrastructure for custom session backends.

sessions gorilla/sessions provides cookie and filesystem sessions and infrastructure for custom session backends. The key features are: Simple API: us

Dec 28, 2022
An imaginary authentication and session tracking service that is defined in this Apiary

Userland This repository contains impelementation of "Userland" on boarding project Userland is an imaginary authentication and session tracking servi

Dec 5, 2021
Auth Middleware for session & white-listed routing

Auth Middleware for session & white-listed routing

Nov 4, 2021
🍪CookieMonster is a command-line tool and API for decoding and modifying vulnerable session cookies from several different frameworks.

?? CookieMonster CookieMonster is a command-line tool and API for decoding and modifying vulnerable session cookies from several different frameworks.

Jan 8, 2023
Advent of Code Input Loader, provide a session cookie and a problem date, returns a string or []byte of the input

Advent of Code Get (aocget) A small lib to download your puzzle input for a given day. Uses your session token to authenticate to obtain your personal

Dec 9, 2021
Ginx - Evilginx2 - A man-in-the-middle attack framework used for phishing login credentials along with session cookies
Ginx - Evilginx2 - A man-in-the-middle attack framework used for phishing login credentials along with session cookies

evilginx2 is a man-in-the-middle attack framework used for phishing login creden

Mar 19, 2022
Basic and Digest HTTP Authentication for golang http

HTTP Authentication implementation in Go This is an implementation of HTTP Basic and HTTP Digest authentication in Go language. It is designed as a si

Dec 22, 2022
HTTP-server-with-auth# HTTP Server With Authentication

HTTP-server-with-auth# HTTP Server With Authentication Introduction You are to use gin framework package and concurrency in golang and jwt-go to imple

Nov 9, 2022
simple-jwt-provider - Simple and lightweight provider which exhibits JWTs, supports login, password-reset (via mail) and user management.

Simple and lightweight JWT-Provider written in go (golang). It exhibits JWT for the in postgres persisted user, which can be managed via api. Also, a password-reset flow via mail verification is available. User specific custom-claims also available for jwt-generation and mail rendering.

Dec 18, 2022
Simple authentication and books management with GoFiber

Simple authentication and books management with GoFiber Simple authentication system with gofiber. Endpoints GET /api - Welcome message POST /api/auth

Nov 27, 2022
BK-IAM is a centralized permission management service provided by The Tencent BlueKing; based on ABAC

(English Documents Available) Overview 蓝鲸权限中心(BK-IAM)是蓝鲸智云提供的集中权限管理服务,支持基于蓝鲸开发框架的SaaS和企业第三方系统的权限控制接入,以及支持细粒度的权限管理。 架构设计 代码目录 Features 蓝鲸权限中心是基于 ABAC 强

Nov 16, 2022
Backend Development Rest Api Project for book management system. Used Features like redis, jwt token,validation and authorization.

Golang-restapi-project Simple Rest Api Project with Authentication, Autherization,Validation and Connection with redis File Structure ├── cache │ ├──

May 25, 2022
Golang based User creation and Management application. GORM, Fiber, JWT

User Creation and Management app (BACK-END) Auth Features: Create Clients (regular password + 6 one-time passwords + (optional) QR code and Secret for

Dec 2, 2022
The boss of http auth.
The boss of http auth.

Authboss Authboss is a modular authentication system for the web. It has several modules that represent authentication and authorization features that

Jan 6, 2023
HTTP Authentication middlewares

goji/httpauth httpauth currently provides HTTP Basic Authentication middleware for Go. It is compatible with Go's own net/http, goji, Gin & anything t

Dec 23, 2022
This package provides json web token (jwt) middleware for goLang http servers

jwt-auth jwt auth middleware in goLang. If you're interested in using sessions, checkout my sessions library! README Contents: Quickstart Performance

Dec 5, 2022