Go (lang) HTTP session authentication

Overview

Go Session Authentication

Build Status Coverage Status GoDoc Version 2.0.0

See git tags/releases for information about potentially breaking change.

This package uses the Gorilla web toolkit's sessions package to implement a user authentication and authorization system for Go web servers.

Multiple user data storage backends are available, and new ones can be implemented relatively easily.

Access can be restricted by a users' role.

Uses bcrypt for password hashing.

var (
    aaa httpauth.Authorizer
)

func login(rw http.ResponseWriter, req *http.Request) {
    username := req.PostFormValue("username")
    password := req.PostFormValue("password")
    if err := aaa.Login(rw, req, username, password, "/"); err != nil && err.Error() == "already authenticated" {
        http.Redirect(rw, req, "/", http.StatusSeeOther)
    } else if err != nil {
        fmt.Println(err)
        http.Redirect(rw, req, "/login", http.StatusSeeOther)
    }
}

Run go run server.go from the examples directory and visit localhost:8009 for an example. You can login with the username "admin" and password "adminadmin".

Tests can be run by simulating Travis CI's build environment. There's a very unsafe script --- start-test-env.sh that will do this for you.

You should follow me on Twitter. Appreciate this package?

TODO

  • User roles - modification
  • SMTP email validation (key based)
  • More backends
  • Possible remove dependance on bcrypt
Issues
  • Minor bug fix

    Minor bug fix

    Moreover err.Error() == "already authenticated" will never match because err.Error() is actually "httpauth: already authenticated". Hence used strings.Contains() instead of direct string comparison.

    Also the case where err == nil was not handled.

    opened by anoopengineer 7
  • Can't update user email on mongodb

    Can't update user email on mongodb

    Tests failing - https://github.com/apexskier/httpauth/blob/mjhall-mongodb/mongoBackend_test.go#L175

    Updating user data results in incorrect user email for mongodb.

    bug 
    opened by apexskier 6
  • Can't create secondary mongodb connection

    Can't create secondary mongodb connection

    Tests failing - https://github.com/apexskier/httpauth/blob/mjhall-mongodb/mongoBackend_test.go#L70

    The intent of this test is to connect to an existing mongoldb with saved data and pull correct info out of it.

    bug 
    opened by apexskier 5
  • Fixes fall-through check for previous user authentication

    Fixes fall-through check for previous user authentication

    Comparing session.Values["username"] != nil will match any value, not only the username of a previously authenticated user. This resulted in "already authenticated" being returned even when no authentication had taken place, as Values["username"] simply was not nil.

    Comparing directly to the passed username value with == u fixes this issue.

    opened by bkrem 4
  • Increase bcrypt cost

    Increase bcrypt cost

    You use a bcrypt cost of 8 (https://github.com/apexskier/httpauth/blob/master/auth.go#L177). Go's default bcrypt cost is 10 (https://github.com/golang/crypto/blob/master/bcrypt/bcrypt.go#L23). Not really an important issue. You may want to make this configurable.

    opened by 0xdabbad00 4
  • fix import path golang.org/x/crypt & format with

    fix import path golang.org/x/crypt & format with "go fmt"

    Import path for bcrypt has been changed to golang.org/x/crypto/bcrypt.

    The rest of the changes are due to automatically "go fmt" that should be done for all go source files.

    opened by h12w 3
  • Add functionality to

    Add functionality to "Update" to allow the username to be specified.

    When using this package for go-ping-sites I ran into a need to update the properties of a user who is not the current session user. For example the scenario in question is when an admin user needs to update another users's properties. Currently it will only update the in-session user. In this modification it allows specifying the user by passing the username for the new behavior or passing as an empty string for the username which will keep the current behavior of getting from the session user. Tests were also added for this case and the example was updated accordingly.

    I also made a couple of minor changes to the gobflie and leveldb tests which were failing for me on Windows due to errors about files being used on subsequent tests.

    opened by turnkey-commerce 2
  • Enable Sourcegraph

    Enable Sourcegraph

    I want to use Sourcegraph code search and code review with httpauth. A project maintainer needs to enable it to set up a webhook so the code is up-to-date there.

    Could you please enable httpauth on @Sourcegraph by going to https://sourcegraph.com/github.com/apexskier/httpauth and clicking on Settings? (It should only take 15 seconds.)

    Thank you!

    opened by kizbitz 1
  • Integrate Recent Change in User Update into Example

    Integrate Recent Change in User Update into Example

    This change is mainly to show in the example how to create a default user without directly accessing the bcrypt implementation, especially in case the bcrypt implementation changes in the future. In this case the API is used to create the user and then update the user password and email via the update feature.

    opened by turnkey-commerce 0
  • Return an error on delete if user doesn't exist.

    Return an error on delete if user doesn't exist.

    This gives more information to the programmer, and could let them catch bugs somewhere else quicker.

    Just safer overall to let any suspicious behavior be known.

    opened by apexskier 0
  • Implement secure cookie

    Implement secure cookie

    This PR resolves #33. By default the secure cookie option is set when the NewAuthorizer() is called. To turn it off a special function called AllowInsecureCookie() will need to be called to set it back to false. Error messages are generated if the secure cookie is on and it the site is served over http.

    The example is updated so that it will work by default on non-https sites but it has been appropriately commented to not do such in production.

    The httpauth version should be incremented since it changes default behavior.

    opened by turnkey-commerce 1
  • Add option to specify secure cookies in the session store

    Add option to specify secure cookies in the session store

    There should be an option to make sure the cookie storage requires secure cookies for sites that have https available. It needs to be optional so that it would be supported in dev/testing environments that don't support https.

    One possibility would be to add another argument to the NewAuthorizer:

    func NewAuthorizer(backend AuthBackend, secureCookie bool, key []byte, defaultRole string, roles map[string]Role) (Authorizer, error) {
        var a Authorizer
        a.cookiejar = sessions.NewCookieStore([]byte(key))
        a.cookiejar.Options.Secure = secureCookie
    ...
    }
    

    or make it secure by default and require calling a Method to make it insecure (best practice):

    func NewAuthorizer(backend AuthBackend, key []byte, defaultRole string, roles map[string]Role) (Authorizer, error) {
        var a Authorizer
        a.cookiejar = sessions.NewCookieStore([]byte(key))
        a.cookiejar.Options.Secure = true
    ...
    }
    
    func (a Authorizer) AllowNonHttpsCookie() {
        a.cookiejar.Options.Secure = false
    }
    

    One related issue to cover is that currently a login seems to fail silently if a.cookiejar.Options.Secure is set to true and it is on a site that does not support https.

    bug enhancement 
    opened by turnkey-commerce 2
  • Started a boltdb backend

    Started a boltdb backend

    Not sure if you are interested in merging it but I started a boltdb backend for this library. I can issue a pull request if you are interested when it is finished and has test code.

    enhancement 
    opened by whatisgravity 3
  • Update error handling to use exported error types instead of relying on checking the string

    Update error handling to use exported error types instead of relying on checking the string

    Checking the string is a very bad idea, and it is a much better idea to create exported error types, such as ErrorAlreadyAuthenticated that we can check for instead of relying on checking the string contents of err.Error(). err.Error() is for the user to read, not the machines.

    http://dave.cheney.net/2016/04/27/dont-just-check-errors-handle-them-gracefully is a good read detailing how it's best to go about this. :-)

    He is also involved in a package that follows the rules he suggests in the blogpost https://github.com/pkg/errors

    enhancement 
    opened by flexd 0
Releases(v1.3.2)
Owner
Cameron Little
I like writing software that helps me out, but I sometimes lack focus. I'm not sure why there's not more React here...
Cameron Little
GLAuth 1.6k Aug 8, 2022
Goauth - Basic username password cookie based authentication with Go Lang

goauth [WIP] Basic username password cookie based authentication with Go Lang Overview Use a Postgres DB to store Sign-in and Sign-up info Redis for c

Joseph Chen 0 Jan 4, 2022
Authelia: an open-source authentication and authorization server providing two-factor authentication

Authelia is an open-source authentication and authorization server providing two

Streato 0 Jan 5, 2022
Authentication Plugin for implementing Form-Based, Basic, Local, LDAP, OpenID Connect, OAuth 2.0, SAML Authentication

Authentication Plugin for implementing Form-Based, Basic, Local, LDAP, OpenID Connect, OAuth 2.0, SAML Authentication

Paul Greenberg 490 Aug 8, 2022
A simple passwordless authentication middleware that uses only email as the authentication provider

email auth A simple passwordless authentication middleware that uses only email as the authentication provider. Motivation I wanted to restrict access

Miroslav Šedivý 5 Jul 27, 2022
Authorization and authentication. Learning go by writing a simple authentication and authorization service.

Authorization and authentication. Learning go by writing a simple authentication and authorization service.

Dinesh Bhattarai 0 Aug 5, 2022
HTTP Session Management for Go

SCS: HTTP Session Management for Go Features Automatic loading and saving of session data via middleware. Choice of server-side session stores includi

Alex Edwards 1.2k Aug 7, 2022
Straightforward HTTP session management

sessionup ?? Simple, yet effective HTTP session management and identification package Features Effortless session management: Initialization. Request

null 117 Jul 25, 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

Lev Shamardin 528 Aug 3, 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

Saba Sahban 12 May 12, 2022
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

András Belicza 107 Jun 1, 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"

Alexey Kuzyashin 26 Feb 13, 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

Gorilla Web Toolkit 2.4k Jul 31, 2022
Auth Middleware for session & white-listed routing

Auth Middleware for session & white-listed routing

Joe Gasewicz 2 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.

Ian Carroll 441 Jul 31, 2022
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

Adrian 0 Dec 9, 2021
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

null 2 Mar 19, 2022
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

Goji 214 Jun 6, 2022
X3 - A template for using HTTP Basic Authentication in Go

HTTP Basic Auth in Go This is a template for using HTTP Basic Auth in a Go appli

Joel Dare 91 May 3, 2022