auth

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

You can read source code of this middleware on GitHubauth - 图1open in new window and API documentation on pkg.go.devauth - 图2open in new window.

Installation

The minimum requirement of Go is 1.16.

  1. go get github.com/flamego/auth

Usage examples

Basic authentication

The auth.Basicauth - 图3open in new window takes a static combination of username and password to protect routes behind it. Upon successful authentication, the auth.Userauth - 图4open in new window is injected into the request context, which simply contains the username:

  1. package main
  2. import (
  3. "github.com/flamego/auth"
  4. "github.com/flamego/flamego"
  5. )
  6. func main() {
  7. f := flamego.Classic()
  8. f.Use(auth.Basic("username", "secretpassword"))
  9. f.Get("/", func(user auth.User) string {
  10. return "Welcome, " + string(user)
  11. })
  12. f.Run()
  13. }

The auth.BasicFuncauth - 图5open in new window can be used to support dynamic combinations of username and password:

  1. package main
  2. import (
  3. "github.com/flamego/auth"
  4. "github.com/flamego/flamego"
  5. )
  6. func main() {
  7. credentials := map[string]string{
  8. "alice": "pa$$word",
  9. "bob": "secretpassword",
  10. }
  11. f := flamego.Classic()
  12. f.Use(auth.BasicFunc(func(username, password string) bool {
  13. return auth.SecureCompare(credentials[username], password)
  14. }))
  15. f.Get("/", func(user auth.User) string {
  16. return "Welcome, " + string(user)
  17. })
  18. f.Run()
  19. }

The auth.SecureCompareauth - 图6open in new window is a function that does constant time compare of two strings to prevent timing attacks.

Bearer authentication

The auth.Bearerauth - 图7open in new window takes a static token to protect routes behind it. Upon successful authentication, the auth.Tokenauth - 图8open in new window is injected into the request context, which simply contains the token:

  1. package main
  2. import (
  3. "github.com/flamego/auth"
  4. "github.com/flamego/flamego"
  5. )
  6. func main() {
  7. f := flamego.Classic()
  8. f.Use(auth.Bearer("secrettoken"))
  9. f.Get("/", func(token auth.Token) string {
  10. return "Authenticated through " + string(token)
  11. })
  12. f.Run()
  13. }

The auth.BearerFuncauth - 图9open in new window can be used to support dynamic tokens:

  1. package main
  2. import (
  3. "github.com/flamego/auth"
  4. "github.com/flamego/flamego"
  5. )
  6. func main() {
  7. tokens := map[string]struct{}{
  8. "token": {},
  9. "secrettoken": {},
  10. }
  11. f := flamego.Classic()
  12. f.Use(auth.BearerFunc(func(token string) bool {
  13. _, ok := tokens[token]
  14. return ok
  15. }))
  16. f.Get("/", func(token auth.Token) string {
  17. return "Authenticated through " + string(token)
  18. })
  19. f.Run()
  20. }