seshcookie

package module
v2.3.1+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 17, 2017 License: MIT Imports: 16 Imported by: 6

README

Build Status GoDoc cover.run go Go Report Card

seshcookie enables you to associate session-state with HTTP requests while keeping your server stateless. Because session-state is transferred as part of the HTTP request (in a cookie), state can be seamlessly maintained between server restarts or load balancing. It's inspired by Beaker, which provides a similar service for Python webapps. The cookies are authenticated and encrypted (using AES-GCM) with a key derived from a string provided to the NewHandler function. This makes seshcookie reliable and secure: session contents are opaque to users and not able to be manipulated or forged by third parties.

examples

The simple example below returns different content based on whether the user has visited the site before or not:

package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/bpowers/seshcookie"
)

type VisitedHandler struct{}

func (h *VisitedHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	if req.URL.Path != "/" {
		return
	}

	session := seshcookie.GetSession(req.Context())

	count, _ := session["count"].(int)
	count++
	session["count"] = count

	rw.Header().Set("Content-Type", "text/plain")
	rw.WriteHeader(200)
	if count == 1 {
		rw.Write([]byte("this is your first visit, welcome!"))
	} else {
		rw.Write([]byte(fmt.Sprintf("page view #%d", count)))
	}
}

func main() {
	key := "session key, preferably a sequence of data from /dev/urandom"
	http.Handle("/", seshcookie.NewHandler(
		&VisitedHandler{},
		key,
		&seshcookie.Config{HTTPOnly: true, Secure: false}))

	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatalf("ListenAndServe: %s", err)
	}
}

There is a more detailed example in example/ which uses seshcookie to enforce authentication for a particular resource. In particular, it shows how you can embed (or stack) multiple http.Handlers to get the behavior you want.

license

seshcookie is offered under the MIT license, see LICENSE for details.

Documentation

Overview

Package seshcookie enables you to associate session-state with HTTP requests while keeping your server stateless. Because session-state is transferred as part of the HTTP request (in a cookie), state can be seamlessly maintained between server restarts or load balancing. It's inspired by Beaker (http://pypi.python.org/pypi/Beaker), which provides a similar service for Python webapps. The cookies are authenticated and encrypted (using AES-GCM) with a key derived from a string provided to the NewHandler function. This makes seshcookie reliable and secure: session contents are opaque to users and not able to be manipulated or forged by third parties.

Storing session-state in a cookie makes building some apps trivial, like this example that tells a user how many times they have visited the site:

package main

import (
	"net/http"
	"log"
	"fmt"

	"github.com/bpowers/seshcookie"
)

type VisitedHandler struct{}

func (h *VisitedHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	if req.URL.Path != "/" {
		return
	}

	session := seshcookie.GetSession(req.Context())

	count, _ := session["count"].(int)
	count++
	session["count"] = count

	rw.Header().Set("Content-Type", "text/plain")
	rw.WriteHeader(200)
	if count == 1 {
		rw.Write([]byte("this is your first visit, welcome!"))
	} else {
		rw.Write([]byte(fmt.Sprintf("page view #%d", count)))
	}
}

func main() {
	key := "session key, preferably a sequence of data from /dev/urandom"
	http.Handle("/", seshcookie.NewHandler(
		&VisitedHandler{},
		key,
		&seshcookie.Config{HTTPOnly: true, Secure: false}))

	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatalf("ListenAndServe: %s", err)
	}
}

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultConfig is used as the configuration if a nil config
	// is passed to NewHandler
	DefaultConfig = &Config{
		CookieName: defaultCookieName,
		CookiePath: "/",
		HTTPOnly:   true,
		Secure:     true,
	}
)

Functions

This section is empty.

Types

type Config

type Config struct {
	CookieName string // name of the cookie to store our session in
	CookiePath string // resource path the cookie is valid for
	HTTPOnly   bool   // don't allow JavaScript to access cookie
	Secure     bool   // only send session over HTTPS
}

Config provides directives to a seshcookie instance on cookie attributes, like if they are accessible from JavaScript and/or only set on HTTPS connections.

type Handler

type Handler struct {
	http.Handler
	Config Config
	// contains filtered or unexported fields
}

Handler is the seshcookie HTTP handler that provides a Session object to child handlers.

func NewHandler

func NewHandler(handler http.Handler, key string, config *Config) *Handler

NewHandler creates a new seshcookie Handler with a given encryption key and configuration.

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request)

type Session

type Session map[string]interface{}

Session is simply a map of keys to arbitrary values, with the restriction that the value must be GOB-encodable.

func GetSession

func GetSession(ctx context.Context) Session

GetSession is a wrapper to grab the seshcookie Session out of a Context.

By only providing a 'Get' API, we ensure that clients can't mistakenly set something unexpected on the given context in place of the session.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL