Basic Auth

Basic auth middleware provides an HTTP basic authentication. It calls the next handler for valid credentials and 401 Unauthorized for missing or invalid credentials.

Installation

  1. go get -u github.com/gofiber/basicauth

Signature

  1. basicauth.New(config ...Config) func(*fiber.Ctx)

Config

PropertyTypeDescriptionDefault
Filterfunc(fiber.Ctx) boolDefines a function to skip middlewarenil
Usersmap[string][string]Users defines the allowed credentialsnil
RealmstringRealm is a string to define the realm attributeRestricted
Authorizerfunc(string, string) boolA function you can pass to check the credentials however you want.nil
Unauthorizedfunc(fiber.Ctx)Custom response body for unauthorized responsesnil

Example

  1. package main
  2.  
  3. import (
  4. "github.com/gofiber/fiber"
  5. "github.com/gofiber/basicauth"
  6. )
  7.  
  8. func main() {
  9. app := fiber.New()
  10.  
  11. cfg := basicauth.Config{
  12. Users: map[string]string{
  13. "john": "doe",
  14. "admin": "123456",
  15. },
  16. }
  17. app.Use(basicauth.New(cfg))
  18.  
  19. app.Get("/", func(c *fiber.Ctx) {
  20. c.Send("Welcome!")
  21. })
  22.  
  23. app.Listen(3000)
  24. }