• Stars
    star
    77
  • Rank 401,709 (Top 9 %)
  • Language
    Go
  • License
    MIT License
  • Created about 7 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A dead simple, highly performant, highly customizable sessions middleware for go http servers.

Build Status Coverage Status Go Report Card GoDoc

If you're interested in jwt's, see my jwt library!

Sessions

A dead simple, highly performant, highly customizable sessions service for go http servers.

By default, the service stores sessions in redis, and transports sessions to clients in cookies. However, these are easily customizeable. For instance, the storage interface only implements three methods:

// ServiceInterface defines the behavior of the session store
type ServiceInterface interface {
	SaveUserSession(userSession *user.Session) error
	DeleteUserSession(sessionID string) error
	FetchValidUserSession(sessionID string) (*user.Session, error)
}

README Contents:

  1. Quickstart
  2. Performance
  3. Design
  4. API
  5. Test Coverage
  6. Example
  7. License

Quickstart

var sesh *sessions.Service

// issue a new session and write the session to the ResponseWriter
userSession, err := sesh.IssueUserSession("fakeUserID", "{\"foo\":\"bar\"}", w)
if err != nil {
	log.Printf("Err issuing user session: %v\n", err)
	http.Error(w, "Internal Server Error", http.StatusInternalServerError)
	return
}

...

// Fetch a pointer to a valid user session from a request. A nil pointer indicates no or invalid session
userSession, err := sesh.GetUserSession(r)
if err != nil {
	log.Printf("Err fetching user session: %v\n", err)
	http.Error(w, "Internal Server Error", http.StatusInternalServerError)
	return
}
// nil session pointers indicate a 401 unauthorized
if userSession == nil {
	http.Error(w, "Unathorized", http.StatusUnauthorized)
	return
}

...

// Extend session expiry. Note that session expiry's need to be manually extended
if err := sesh.ExtendUserSession(userSession, r, w); err != nil {
	log.Printf("Err extending user session: %v\n", err)
	http.Error(w, "Internal Server Error", http.StatusInternalServerError)
	return
}

...

// Invalidate a user session, deleting it from redis and expiring the cookie on the ResponseWriter
if err := sesh.ClearUserSession(userSession, w); err != nil {
	log.Printf("Err clearing user session: %v\n", err)
	http.Error(w, "Internal Server Error", http.StatusInternalServerError)
	return
}

Performance

Benchmarks require a redis-server running. Set the REDIS_URL environment variable, otherwise the benchmarks look for ":6379".

YMMV

$ (cd benchmark && go test -bench=.)

setting up benchmark tests
BenchmarkBaseServer-2              20000             72479 ns/op
BenchmarkValidSession-2            10000            151650 ns/op
PASS
shutting down benchmark tests
ok      github.com/adam-hanna/sessions/benchmark        3.727s

Design

By default, the service stores sessions in redis, and transports hashed sessionIDs to clients in cookies. However, these are easily customizeable through the creation of custom structs that implement the interface.

The general flow of the session service is as follows:

  1. Create store, auth and transport services by calling their respective New(...) functions (or create your own custom services that implement the service's interface methods). Then pass these services to the sessions.New(...) constructor.
  2. After a user logs in, call the sessions.IssueUserSession(...) function. This function first creates a new user.Session. SessionIDs are RFC 4122 version 4 uuids. Next, the service hashes the sessionID with the provided key. The hashing algorithm is SHA-512, and therefore the key used should be between 64 and 128 bytes. Then, the service stores the session in redis and finally writes the hashed sessionID to the response writer in a cookie. Sessions written to the redis db utilize EXPIREAT to automatically destory expired sessions.
  3. To check if a valid session was included in a request, use the sessions.GetUserSession(...) function. This function grabs the hashed sessionID from the session cookie, verifies the HMAC signature and finally looks up the session in the redis db. If the session is expired, or fails HMAC signature verification, this function will return a nil pointer to a user session. If the session is valid, and you'd like to extend the session's expiry, you can then call session.ExtendUserSession(...). Session expiry's are never automatically extended, only through calling this function will the session's expiry be extended.
  4. When a user logs out, call the sessions.ClearUserSession(...) function. This function destroys the session in the db and also destroys the cookie on the ResponseWriter.

API

type Session struct {
	ID        string
	UserID    string
	ExpiresAt time.Time
	JSON      string
}

Session is the struct that is used to store session data. The JSON field allows you to set any custom information you'd like. See the example

func (s *Service) IssueUserSession(userID string, json string, w http.ResponseWriter) (*user.Session, error)

IssueUserSession grants a new user session, writes that session info to the store and writes the session on the http.ResponseWriter.

This method should be called when a user logs in, for example.

func (s *Service) ClearUserSession(userSession *user.Session, w http.ResponseWriter) error

ClearUserSession is used to remove the user session from the store and clear the cookies on the ResponseWriter.

This method should be called when a user logs out, for example.

func (s *Service) GetUserSession(r *http.Request) (*user.Session, error)

GetUserSession returns a user session from the hashed sessionID included in the request. This method only returns valid sessions. Therefore, sessions that have expired or that fail signature verification will return a nil pointer.

func (s *Service) ExtendUserSession(userSession *user.Session, r *http.Request, w http.ResponseWriter) error

ExtendUserSession extends the ExpiresAt of a session by the Options.ExpirationDuration

Note that this function must be called, manually! Extension of user session expiry's does not happen automatically!

Testing Coverage

ok      github.com/adam-hanna/sessions			9.012s  coverage: 94.1% of statements
ok      github.com/adam-hanna/sessions/auth		0.003s  coverage: 100.0% of statements
ok      github.com/adam-hanna/sessions/store		0.006s  coverage: 85.4% of statements
ok      github.com/adam-hanna/sessions/benchmark	0.004s  coverage: 0.0% of statements [no tests to run]
ok      github.com/adam-hanna/sessions/transport	0.004s  coverage: 95.2% of statements
ok      github.com/adam-hanna/sessions/user		0.003s  coverage: 100.0% of statements

Tests are broken down into three categories: unit, integration and e2e. Integration and e2e tests require a connection to a redis server. The connection address can be set in the REDIS_URL environment variable. The default is ":6379".

To run all tests, simply:

$ go test -tags="unit integration e2e" ./...

// or
$ make test

// or
$ make test-cover-html && go tool cover -html=coverage-all.out

To run only tests from one of the categories:

$ go test -tags="integration" ./...

To run only unit and integration tests:

$ go test -tags="unit integration" ./...

Example

The following example is a demonstration of using the session service along with a CSRF code to check for authentication. The CSRF code is stored in the user.Session JSON field.

package main

import (
	"crypto/rand"
	"encoding/base64"
	"encoding/json"
	"io"
	"log"
	"net/http"
	"time"

	"github.com/adam-hanna/sessions"
	"github.com/adam-hanna/sessions/auth"
	"github.com/adam-hanna/sessions/store"
	"github.com/adam-hanna/sessions/transport"
)

// SessionJSON is used for marshalling and unmarshalling custom session json information.
// We're using it as an opportunity to tie csrf strings to sessions to prevent csrf attacks
type SessionJSON struct {
	CSRF string `json:"csrf"`
}

var sesh *sessions.Service

var issueSession = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	csrf, err := generateKey()
	if err != nil {
		log.Printf("Err generating csrf: %v\n", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	myJSON := SessionJSON{
		CSRF: csrf,
	}
	JSONBytes, err := json.Marshal(myJSON)
	if err != nil {
		log.Printf("Err marhsalling json: %v\n", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	userSession, err := sesh.IssueUserSession("fakeUserID", string(JSONBytes[:]), w)
	if err != nil {
		log.Printf("Err issuing user session: %v\n", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}
	log.Printf("In issue; user's session: %v\n", userSession)

	// note: we set the csrf in a cookie, but look for it in request headers
	csrfCookie := http.Cookie{
		Name:     "csrf",
		Value:    csrf,
		Expires:  userSession.ExpiresAt,
		Path:     "/",
		HttpOnly: false,
		Secure:   false, // note: can't use secure cookies in development
	}
	http.SetCookie(w, &csrfCookie)

	w.WriteHeader(http.StatusOK)
})

var requiresSession = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	userSession, err := sesh.GetUserSession(r)
	if err != nil {
		log.Printf("Err fetching user session: %v\n", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}
	// nil session pointers indicate a 401 unauthorized
	if userSession == nil {
		http.Error(w, "Unathorized", http.StatusUnauthorized)
		return
	}
	log.Printf("In require; user session expiration before extension: %v\n", userSession.ExpiresAt.UTC())

	myJSON := SessionJSON{}
	if err := json.Unmarshal([]byte(userSession.JSON), &myJSON); err != nil {
		log.Printf("Err unmarshalling json: %v\n", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	log.Printf("In require; user's custom json: %v\n", myJSON)

	// note: we set the csrf in a cookie, but look for it in request headers
	csrf := r.Header.Get("X-CSRF-Token")
	if csrf != myJSON.CSRF {
		log.Printf("Unauthorized! CSRF token doesn't match user session")
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}

	// note that session expiry's need to be manually extended
	if err = sesh.ExtendUserSession(userSession, r, w); err != nil {
		log.Printf("Err extending user session: %v\n", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}
	log.Printf("In require; users session expiration after extension: %v\n", userSession.ExpiresAt.UTC())

	// need to extend the csrf cookie, too
	csrfCookie := http.Cookie{
		Name:     "csrf",
		Value:    csrf,
		Expires:  userSession.ExpiresAt,
		Path:     "/",
		HttpOnly: false,
		Secure:   false, // note: can't use secure cookies in development
	}
	http.SetCookie(w, &csrfCookie)

	w.WriteHeader(http.StatusOK)
})

var clearSession = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	userSession, err := sesh.GetUserSession(r)
	if err != nil {
		log.Printf("Err fetching user session: %v\n", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}
	// nil session pointers indicate a 401 unauthorized
	if userSession == nil {
		http.Error(w, "Unathorized", http.StatusUnauthorized)
		return
	}

	log.Printf("In clear; session: %v\n", userSession)

	myJSON := SessionJSON{}
	if err := json.Unmarshal([]byte(userSession.JSON), &myJSON); err != nil {
		log.Printf("Err unmarshalling json: %v\n", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}
	log.Printf("In require; user's custom json: %v\n", myJSON)

	// note: we set the csrf in a cookie, but look for it in request headers
	csrf := r.Header.Get("X-CSRF-Token")
	if csrf != myJSON.CSRF {
		log.Printf("Unauthorized! CSRF token doesn't match user session")
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}

	if err = sesh.ClearUserSession(userSession, w); err != nil {
		log.Printf("Err clearing user session: %v\n", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	// need to clear the csrf cookie, too
	aLongTimeAgo := time.Now().Add(-1000 * time.Hour)
	csrfCookie := http.Cookie{
		Name:     "csrf",
		Value:    "",
		Expires:  aLongTimeAgo,
		Path:     "/",
		HttpOnly: false,
		Secure:   false, // note: can't use secure cookies in development
	}
	http.SetCookie(w, &csrfCookie)

	w.WriteHeader(http.StatusOK)
})

func main() {
	seshStore := store.New(store.Options{})

	// e.g. `$ openssl rand -base64 64`
	seshAuth, err := auth.New(auth.Options{
		Key: []byte("DOZDgBdMhGLImnk0BGYgOUI+h1n7U+OdxcZPctMbeFCsuAom2aFU4JPV4Qj11hbcb5yaM4WDuNP/3B7b+BnFhw=="),
	})
	if err != nil {
		log.Fatal(err)
	}

	seshTransport := transport.New(transport.Options{
		HTTPOnly: true,
		Secure:   false, // note: can't use secure cookies in development!
	})

	sesh = sessions.New(seshStore, seshAuth, seshTransport, sessions.Options{})

	http.HandleFunc("/issue", issueSession)
	http.HandleFunc("/require", requiresSession)
	http.HandleFunc("/clear", clearSession) // also requires a valid session

	log.Println("Listening on localhost:3000")
	log.Fatal(http.ListenAndServe("127.0.0.1:3000", nil))
}

// thanks
// https://astaxie.gitbooks.io/build-web-application-with-golang/en/06.2.html#unique-session-ids
func generateKey() (string, error) {
	b := make([]byte, 16)
	if _, err := io.ReadFull(rand.Reader, b); err != nil {
		return "", err
	}
	return base64.URLEncoding.EncodeToString(b), nil
}

License

The MIT License (MIT)

Copyright (c) 2017 Adam Hanna

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

More Repositories

1

jwt-auth

This package provides json web token (jwt) middleware for goLang http servers
Go
231
star
2

goLang-jwt-auth-example

This is an example implementation of jwt auth with goLang
Go
110
star
3

arrayOperations

Small library for performing union, intersect, difference and distinct operations on slices in goLang
Go
89
star
4

react-responsive-tables

A react component for responsive tables
JavaScript
52
star
5

goal-seek

goal-seek is a javascript library that can be used to solve for the value of an independent variable: "x"; of a function: "f(x)"; such that f(x) equals some defined goal. In other words: do you know the desired output of a function but not the input to yield such an output? If so, then use this goal seek!
TypeScript
36
star
6

design-first

A REST api templating engine for typescript.
TypeScript
34
star
7

golang-vuejs-starter-kit

This is a starter kit for goLang and vuejs which can be cloned to start your next project
JavaScript
29
star
8

lwan-mustache-c

The mustache templating engine from the lwan http server written in C
C
8
star
9

securitiesOption.js

securitiesOption.js is a javascript library for evaluating option prices and implied volatilities using Cox Ross Rubinstein (CRR), trinomial trees or Black-Scholes
JavaScript
8
star
10

PDQdb

A read-optimized, in-memory, columnar store database (column-oriented DBMS)
Go
5
star
11

c-vs-goLang-Quicksort

Testing the performance of quicksort in c and goLang
C
5
star
12

httb

An http benchmarking tool written in go
Go
3
star
13

design-first-example

Example with postgres, redis, and passport.js sessions
TypeScript
3
star
14

redis-sessions

A plugin for github.com/RichardKnop/go-oauth2-server that provides redis storage for sessions
Go
2
star
15

vue-router-cordova

A non-working example of vue v2, vue-router and cordova
JavaScript
1
star
16

randomStrings

Generate random strings in goLang
Go
1
star
17

gretl

A fork of the GNU Regression, Econometrics and Time-series Library (GRETL)
C
1
star
18

btc_address_validator

A BTC public address validator sourced from rosettacode.org
Go
1
star
19

vgo-bug

Demo repo of a bug in vgo
Go
1
star
20

copyRecursive

Recursively copy structs in goLang
Go
1
star
21

McClaneScript

McClaneScript is a new syntax for javascript. Now, write all of your code with one-liners from John McClane in Die Hard!
JavaScript
1
star