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
The minimum requirement of Go is 1.16.
go get github.com/flamego/auth
Usage examples
Basic authentication
The auth.Basic
open in new window takes a static combination of username and password to protect routes behind it. Upon successful authentication, the auth.User
open 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.BasicFunc
open 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.SecureCompare
open in new window is a function that does constant time compare of two strings to prevent timing attacks.
Bearer authentication
The auth.Bearer
open in new window takes a static token to protect routes behind it. Upon successful authentication, the auth.Token
open 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.BearerFunc
open 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()
}