auth

The auth middleware provides request authentication for Flame instances, including basic and bearer authentications.

You can read source code of this middleware on GitHubopen in new window and API documentation on pkg.go.devopen in new window.

Installation

go get github.com/flamego/auth

Usage examples

Basic authentication

The auth.Basicopen in new window takes a static combination of username and password to protect routes behind it. Upon successful authentication, the auth.Useropen in new window is injected into the request context, which simply contains the username:

package main

import (
	"github.com/flamego/auth"
	"github.com/flamego/flamego"
)

func main() {
	f := flamego.Classic()
	f.Use(auth.Basic("username", "secretpassword"))
	f.Get("/", func(user auth.User) string {
		return "Welcome, " + string(user)
	})
	f.Run()
}

The auth.BasicFuncopen in new window can be used to support dynamic combinations of username and password:

package main

import (
	"github.com/flamego/auth"
	"github.com/flamego/flamego"
)

func main() {
	credentials := map[string]string{
		"alice": "pa$$word",
		"bob":   "secretpassword",
	}

	f := flamego.Classic()
	f.Use(auth.BasicFunc(func(username, password string) bool {
		return auth.SecureCompare(credentials[username], password)
	}))
	f.Get("/", func(user auth.User) string {
		return "Welcome, " + string(user)
	})
	f.Run()
}















 






The auth.SecureCompareopen in new window is a function that does constant time compare of two strings to prevent timing attacks.

Bearer authentication

The auth.Beareropen in new window takes a static token to protect routes behind it. Upon successful authentication, the auth.Tokenopen in new window is injected into the request context, which simply contains the token:

package main

import (
	"github.com/flamego/auth"
	"github.com/flamego/flamego"
)

func main() {
	f := flamego.Classic()
	f.Use(auth.Bearer("secrettoken"))
	f.Get("/", func(token auth.Token) string {
		return "Authenticated through " + string(token)
	})
	f.Run()
}

The auth.BearerFuncopen in new window can be used to support dynamic tokens:

package main

import (
	"github.com/flamego/auth"
	"github.com/flamego/flamego"
)

func main() {
	tokens := map[string]struct{}{
		"token":       {},
		"secrettoken": {},
	}

	f := flamego.Classic()
	f.Use(auth.BearerFunc(func(token string) bool {
		_, ok := tokens[token]
		return ok
	}))
	f.Get("/", func(token auth.Token) string {
		return "Authenticated through " + string(token)
	})
	f.Run()
}