Socket
Socket
Sign inDemoInstall

github.com/rivo/sessions

Package Overview
Dependencies
0
Alerts
File Explorer

Install Socket

Detect and block malicious and high-risk dependencies

Install

    github.com/rivo/sessions

Package sessions provides tools to manage cookie-based web sessions. Special emphasis is placed on security by implementing OWASP recommendations, specifically the following features: In addition, the package provides the following functionality: While simple to use, the package offers a number of extensively documented configuration variables. It also does not assume specific backend technologies. That is, any session storage system may be used simply by implementing the PersistenceLayer interface (or parts of it). This package is currently not written to be run on multiple machines in a distributed fashion without a load balancer that implements sticky sessions. This may change in the future. Although some more configuration needs to happen for production readiness, the package's defaults allow you to get started very quickly. To get access to the current session, simply call Start(): By providing "true" instead of "false" to the Start() function, you can force the creation of a session, even if there previously was none. Once you have a session, you can identify a user across multiple HTTP requests. You may add values to the session, attach a user to it, cause its session ID to change, or destroy it again. For more extensive user-centered functions (for example, signing up, logging in and out, changing passwords etc.), see the subdirectory "users". Before putting your application into production, you must implement the NewSessionCookie function: You may choose a different expiry date, domain, and path but the other fields are mandatory (given that you are using TLS which you certainly should). You can change the name of the cookie by changing the SessionCookie variable. The default is the inconspicuous string "id". The following timeout values may be adjusted according to the requirements of your application: To further reduce the risk of session hijacking attacks, this package checks client IP addresses as well as user agent strings and destroys sessions if changes in these properties were detected. Refer to the AcceptRemoteIP and AcceptChangingUserAgent variables for more information. Sessions are stored in a local RAM cache (which is a simpe map) whose size is defined by the MaxSessionCacheSize variable. If you set this variable to 0, no sessions are held locally. The SessionCacheExpiry controls when a session will be purged from the cache based on the last time it was used. The cache is write-through (except for session last access times). That is, every time a change was made to a session, that change is forwarded to the package's persistence layer to be saved. The persistence layer is a collection of functions which allow the storage and retrieval of objects from a permanent data store. For example, you may use an SQL database or a key-value store. See the documentation of PersistenceLayer for details on the functions to be implemented. If you need to implement only some of the functions, you may use ExtendablePersistenceLayer instead of creating your own class. The package default is to do nothing. That is, sessions are not persisted and therefore will get lost when purged from the local cache or when the application exits. Session objects implement gob.GobEncoder/gob.GobDecoder and json.Marshaler/json.Unmarshaler. While encoding to JSON allows you to easily inspect session attributes in your database, GOB serialization is preferred as it will restore session objects precisely. (For example, the JSON package always unmarshals numbers into floats even if they were originally integers.) It is recommended that you purge your data store from expired sessions from time to time, e.g. by using a cron job, because users may abandon your website which will leave old sessions in your store. It is recommended to call PurgeSessions() before exiting the program. This will cause session last access times to be updated. This package provides a number of utility functions which may be useful in the context of session and user management. The CUID() function generates Base-62 "compact unique identifiers" suitable for user IDs. The RandomID() function generates random Base-62 strings of any length. The ReasonablePassword() function checks the strength of a password based on the recommendations of NIST SP 800-63B.


Version published

Readme

Source

Godoc Reference Go Report

This Go package attempts to free you from the hard work of implementing safe cookie-based web sessions.

Sessions implements a number of OWASP recommendations:

  • No data storage on the client
  • Automatic session expiry
  • Session ID regeneration
  • Anomaly detection via IP address and user agent analysis

Additional features:

  • Session key/value storage
  • Log in/out functions for users
  • Various identifier generation functions
  • Password strength checks (based on NIST recommendations)
  • Lots of configuration options
  • Database-agnostic, choose your own backend
  • It's not a framework, everything is based on net/http.
  • Extensive documentation

If you want to go one step further and have user signup, login, logout, password reset, email/password change implemented for you, check out github.com/rivo/users.

Installation

go get github.com/rivo/sessions

Simple Example

func MyHandler(response http.ResponseWriter, request *http.Request) {
  session, err := sessions.Start(response, request, false)
  if err != nil {
    panic(err)
  }
  if session != nil {
    fmt.Println("We have a session")
  } else {
    fmt.Println("We have no session")
  }
}

(Providing true will always return a session.)

With the session object, you can call:

  • RegenerateID to switch the session ID,
  • Set, Get, GetAndDelete, and Delete to (un-)assign values to keys,
  • LogIn and LogOut to attach/detach users,
  • GobEncode, GobDecode, MarshalJSON, and UnmarshalJSON to (un-)serialize sessions,
  • Destroy to end a session.

Configuration Options

  • SessionCookie: Name of the session cookie.
  • NewSessionCookie: Function for new cookies (used to set cookie parameters).
  • SessionExpiry: Time to expiry for inactive sessions.
  • SessionIDExpiry: Maximum session ID lifetime before automatic regeneration.
  • SessionIDGracePeriod: Extended lifetime for regenerated session IDs.
  • AcceptRemoteIP: Accepted level of change for IP addresses.
  • AcceptChangingUserAgent: Whether or not user agent changes are accepted.
  • MaxSessionCacheSize: Size of local (write-through) session cache.
  • SessionCacheExpiry: Maximum session lifetime in local cache.

Then there is Persistence used to connect to the session store of your choice (defaults to RAM).

Documentation

See http://godoc.org/github.com/rivo/sessions for the documentation.

See also the Wiki for more examples and explanations.

Your Feedback

Add your issue here on GitHub. Feel free to get in touch if you have any questions.

Release Notes

  • v0.1 (2017-11-11)
    • First release.

FAQs

Last updated on 03 Jul 2022

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc