gowebauth

package module
v0.0.0-...-e14d7ca Latest Latest
Warning

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

Go to latest
Published: Dec 8, 2018 License: MIT Imports: 11 Imported by: 0

README

CircleCI GoDoc Go Report Card Coverage Status

GO Web Auth

Go library for providing middleware for HTTP auth schemes.

Examples

Single-user Basic Auth
package main

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

	"github.com/clagraff/gowebauth"
	"github.com/nbari/violetear"
)

// route writes the requested URL to the HTTP response.
func route(w http.ResponseWriter, r *http.Request) {
	response := []byte(fmt.Sprintf("Successfully hit: %s", r.URL.String()))

	w.Write(response)
}

// main will setup a new HTTP server using gowebauth for authentication.
func main() {
	// Use whatever infrastructure you want. We use violetear only as an example.
	router := violetear.New()

	// Lets specifiy all valid users & create a realm for them
	admin := gowebauth.MakeUser("admin", "Password!")

	// Create middleware to be used by your router
	adminOnly := gowebauth.Handle(admin, route)

	router.Handle("/private", adminOnly, "GET")
	router.HandleFunc("/public", route, "GET")

	log.Panic(http.ListenAndServe(":8080", router))
}
Users and Realms
package main

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

	"github.com/clagraff/gowebauth"
	"github.com/nbari/violetear"
)

// route writes the requested URL to the HTTP response.
func route(w http.ResponseWriter, r *http.Request) {
	response := []byte(fmt.Sprintf("Successfully hit: %s", r.URL.String()))

	w.Write(response)
}

// main will setup a new HTTP server using gowebauth for authentication.
func main() {
	// Use whatever infrastructure you want. We use violetear only as an example.
	router := violetear.New()

	// Lets specifiy all valid users & create a realm for them
	users := []gowebauth.User{
		gowebauth.MakeUser("admin", "Password!"),
		gowebauth.MakeUser("gon", "hunter123"),
		gowebauth.MakeUser("bennett", "qwop"),
	}
	realm, err := gowebauth.MakeRealm("Restricted Page", users)
	if err != nil {
	    panic(err)
    }

	// Wrap route to require authentication.
	privateRoute := gowebauth.Handle(realm, route)

	router.Handle("/private", privateRoute, "GET")
	router.HandleFunc("/public", route, "GET")

	log.Panic(http.ListenAndServe(":8080", router))
}

While any of the examples are running, you can try hitting a route using Curl:

$ curl -v -u admin:Password! localhost:8080/private
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
* Server auth using Basic with user 'admin'
> GET /private HTTP/1.1
> Host: localhost:8080
> Authorization: Basic YWRtaW46UGFzc3dvcmQh
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Thu, 26 Apr 2018 15:17:06 GMT
< Content-Length: 26
< Content-Type: text/plain; charset=utf-8
<
* Connection #0 to host localhost left intact
Successfully hit: /private 
HTTP Digest Auth
package main

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

	"github.com/clagraff/gowebauth"
	"github.com/nbari/violetear"
)

// route writes the requested URL to the HTTP response.
func route(w http.ResponseWriter, r *http.Request) {
	response := []byte(fmt.Sprintf("Successfully hit: %s", r.URL.String()))

	w.Write(response)
}

// main will setup a new HTTP server using gowebauth for authentication.
func main() {
	// Use whatever infrastructure you want. We use violetear only as an example.
	router := violetear.New()

	// Lets specifiy all valid users & create a realm for them
	users := []gowebauth.User{
		gowebauth.MakeUser("admin", "Password!"),
		gowebauth.MakeUser("gon", "hunter123"),
		gowebauth.MakeUser("bennett", "qwop"),
	}
	realm, err := gowebauth.MakeRealm("Restricted Page", users)
	if err != nil {
		panic(err)
	}
	digest := gowebauth.MakeDigest(realm, 15, 300*time.Second)

	// Wrap route to require authentication.
	privateRoute := gowebauth.Handle(digest, route)

	router.Handle("/private", privateRoute, "GET")
	router.HandleFunc("/public", route, "GET")

	log.Panic(http.ListenAndServe(":8080", router))
}

While this example is running, you can try hitting the route and formatting the digest-auth string.

Your exact bash commands will be different as the generated nonce will vary.

$ curl -v localhost:8080/private
curl -v localhost:8080/private
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /private HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 401 Unauthorized
< Www-Authenticate: Basic realm="Restricted Page" charset="utf-8" nonce="ad8fa7b5"
< Date: Wed, 23 May 2018 16:30:19 GMT
< Content-Length: 29
< Content-Type: text/plain; charset=utf-8
<
* Connection #0 to host localhost left intact
malformed authorizationheader
$ echo -n "gon:Restricted Page:hunter123" | md5sum
f6def3aaf5ce8c891e4f74a95fcbf0a1  -
$ echo -n "GET:/private" | md5sum
fda2c070587e883e75df51c06f6c70d2  -
$ echo -n "f6def3aaf5ce8c891e4f74a95fcbf0a1:ad8fa7b5:fda2c070587e883e75df51c06f6c70d2" | md5sum
3a32bfdcd6ba445d611d297f085065c6  -
$ curl -v --header "Authorization: Digest username=\"gon\",realm=\"Restricted Page\",nonce=\"ad8fa7b5\",uri=\"/private\",qop=\"qop\",response=\"3a32bfdcd6ba445d611d297f085065c6\""  localhost:8080/private
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /private HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.54.0
> Accept: */*
> Authorization: Digest username="gon",realm="Restricted Page",nonce="ad8fa7b5",uri="/private",qop="qop",response="3a32bfdcd6ba445d611d297f085065c6"
>
< HTTP/1.1 200 OK
< Date: Wed, 23 May 2018 16:32:27 GMT
< Content-Length: 26
< Content-Type: text/plain; charset=utf-8
<
* Connection #0 to host localhost left intact
Successfully hit: /private

License

MIT License

Copyright (c) 2018 Curtis La Graff

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.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ContextKey = contextKey("Identity")

ContextKey is the key used to store the identity from an IsAuthorized call into a request's context.Context. This is used for middleware and handlers.

Functions

func Handle

func Handle(
	auth Authorizer,
	fn func(http.ResponseWriter, *http.Request),
) http.Handler

Handle can be used with some web frameworks for creating authorization middleware. If a request fails to pass authorization, the authorizer's failure handler is used generate a response, and the request is no longer processed.

func HandlerFunc

func HandlerFunc(
	auth Authorizer,
	fn func(http.ResponseWriter, *http.Request),
) func(http.ResponseWriter, *http.Request)

HandlerFunc can be used with some web frameworks for creating authorization middleware. If a request fails to pass authorization, the authorizer's failure handler is used generate a response, and the request is no longer processed.

func Middleware

func Middleware(auth Authorizer) func(http.Handler) http.Handler

Middleware can be used with some web frameworks for creating authorization middleware. If a request fails to pass authorization, the authorizer's failure handler is used generate a response, and the request is no longer processed.

Types

type Authorizer

type Authorizer interface {
	IsAuthorized(*http.Request) (string, error)
	FailureHandler(error) http.Handler
}

Authorizer specifies an interface which enables performing authentication checks and providing an HTTP failure handler.

type Digest

type Digest struct {
	// contains filtered or unexported fields
}

Digest represents a new HTTP Digest Authentication manager.

func MakeDigest

func MakeDigest(realm Realm, uses int, lifetime time.Duration) Digest

MakeDigest returns an instantiated Digest instance. Specify how many times a nonce can be used, and how long it will last. Expired nonces will be cleaned up automatically.

func (Digest) FailureHandler

func (digest Digest) FailureHandler(authErr error) http.Handler

FailureHandler reponds with a 401 HTTP code, the WWW-Authenticate header, and an error message for HTTP Basic Auth failed requests.

func (Digest) IsAuthorized

func (digest Digest) IsAuthorized(r *http.Request) (string, error)

IsAuthorized checks the authorization to determine if it is a valid HTTP Digest response.

type Realm

type Realm struct {
	Charset string
	Name    string
	// contains filtered or unexported fields
}

Realm represents a collection of Users for a given HTTP Basic Auth realm.

func MakeRealm

func MakeRealm(realm string, users []User) (Realm, error)

MakeRealm creates a new Realm instance for the given realm string and any applicable Users. This will default the Realm's charset is utf-8. If no users are provided, or users share the same username, an error will occur.

func (Realm) FailureHandler

func (realm Realm) FailureHandler(authErr error) http.Handler

FailureHandler reponds with a 401 HTTP code, the WWW-Authenticate header, and an error message for HTTP Basic Auth failed requests.

func (Realm) IsAuthorized

func (realm Realm) IsAuthorized(r *http.Request) (string, error)

IsAuthorized checks the authorization string for a correct scheme & matching username and password for any of the users existing in the current realm.

type User

type User struct {
	// contains filtered or unexported fields
}

User represents a single HTTP Basic Auth username and password pair. Since the username and password of a User are non-exported, you should create a new User using MakeUser(username, password).

func MakeUser

func MakeUser(username, password string) User

MakeUser creates a new User instance with the specified username and plaintext password. Usernames containing any colon characters results in a panic.

func (User) FailureHandler

func (user User) FailureHandler(authErr error) http.Handler

FailureHandler reponds with a 401 HTTP code, the WWW-Authenticate header, and an error message for HTTP Basic Auth failed requests. The realm is set as Restricted with the character set of utf-8. To control these, use a Realm instead.

func (User) IsAuthorized

func (user User) IsAuthorized(r *http.Request) (string, error)

IsAuthorized checks the authorization string for the Basic scheme and a username and password which match the current user.

Jump to

Keyboard shortcuts

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