keyauth

package module
v2.1.30 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2022 License: MIT Imports: 3 Imported by: 11

README

Key Authentication

Release Discord Test Security Linter

Special thanks to József Sallai & Ray Mayemir

Install
go get -u github.com/gofiber/fiber/v2
go get -u github.com/gofiber/keyauth/v2
Example
package main

import (
  "github.com/gofiber/fiber/v2"
  "github.com/gofiber/keyauth/v2"
)

const (
  apiKey = "my-super-secret-key"
)

var (
  errMissing = &fiber.Error{Code: 403, Message: "Missing API key"}
  errInvalid  = &fiber.Error{Code: 403, Message: "Invalid API key"}
)

func validateApiKey(ctx *fiber.Ctx, s string) (bool, error) {
  if s == "" {
    return false, errMissing
  }
  if s == apiKey {
    return true, nil
  }
  return false, errInvalid
}

func main() {
  app := fiber.New()

  app.Use(keyauth.New(keyauth.Config{
    KeyLookup: "cookie:access_token",
    Validator: validateApiKey,
  }))

  app.Get("/", func(c *fiber.Ctx) error {
    return c.SendString("Successfully authenticated!")
  })

  app.Listen(":3000")
}
Test
# No api-key specified -> 400 missing 
curl http://localhost:3000
#> missing or malformed API Key

curl --cookie "access_token=my-super-secret-key" http://localhost:3000
#> Successfully authenticated!

curl --cookie "access_token=Clearly A Wrong Key" http://localhost:3000
#> Invalid or expired API Key

For a more detailed example, see also the github.com/gofiber/recipes repository and specifically the fiber-envoy-extauthz repository and the keyauth example code.

Authenticate only certain endpoints

If you want to authenticate only certain endpoints, you can use the Config of keyauth and apply a filter function (eg. authFilter) like so

package main

import (
  "github.com/gofiber/fiber/v2"
  "github.com/gofiber/keyauth/v2"
)

const (
  apiKey = "my-super-secret-key"
)

var (
  errMissing = &fiber.Error{Code: 403, Message: "Missing API key"}
  errInvalid  = &fiber.Error{Code: 403, Message: "Invalid API key"}
)

func validateApiKey(ctx *fiber.Ctx, s string) (bool, error) {
  if s == "" {
    return false, errMissing
  }
  if s == apiKey {
    return true, nil
  }
  return false, errInvalid
}

func authFilter(c *fiber.Ctx) bool {
  protectedURLs := map[string]interface{}{"/authenticated": nil, "/auth2": nil}
  _, exists := protectedURLs[c.OriginalURL()]
  return !exists
}

func main() {
  app := fiber.New()

  app.Use(keyauth.New(keyauth.Config{
    Filter: authFilter,
    KeyLookup: "cookie:access_token",
    Validator: validateApiKey,
  }))

  app.Get("/", func(c *fiber.Ctx) error {
    return c.SendString("Welcome")
  })
  app.Get("/authenticated", func(c *fiber.Ctx) error {
    return c.SendString("Successfully authenticated!")
  })
  app.Get("/auth2", func(c *fiber.Ctx) error {
    return c.SendString("Successfully authenticated 2!")
  })

  app.Listen(":3000")
}

Which results in this

# / does not need to be authenticated
curl http://localhost:3000
#> Welcome

# /authenticated needs to be authenticated
curl --cookie "access_token=my-super-secret-key" http://localhost:3000/authenticated
#> Successfully authenticated!

# /auth2 needs to be authenticated too
curl --cookie "access_token=my-super-secret-key" http://localhost:3000/auth2
#> Successfully authenticated 2!

Documentation

Overview

🚀 Fiber is an Express inspired web framework written in Go with 💖 📌 API Documentation: https://fiber.wiki 📝 Github Repository: https://github.com/gofiber/fiber Special thanks to Echo: https://github.com/labstack/echo/blob/master/middleware/key_auth.go

Index

Constants

This section is empty.

Variables

View Source
var (
	// When there is no request of the key thrown ErrMissingOrMalformedAPIKey
	ErrMissingOrMalformedAPIKey = errors.New("missing or malformed API Key")
)

Functions

func New

func New(config ...Config) fiber.Handler

New ...

Types

type Config

type Config struct {
	// Filter defines a function to skip middleware.
	// Optional. Default: nil
	Filter func(*fiber.Ctx) bool

	// SuccessHandler defines a function which is executed for a valid key.
	// Optional. Default: nil
	SuccessHandler fiber.Handler

	// ErrorHandler defines a function which is executed for an invalid key.
	// It may be used to define a custom error.
	// Optional. Default: 401 Invalid or expired key
	ErrorHandler fiber.ErrorHandler

	// KeyLookup is a string in the form of "<source>:<name>" that is used
	// to extract key from the request.
	// Optional. Default value "header:Authorization".
	// Possible values:
	// - "header:<name>"
	// - "query:<name>"
	// - "form:<name>"
	// - "param:<name>"
	// - "cookie:<name>"
	KeyLookup string

	// AuthScheme to be used in the Authorization header.
	// Optional. Default value "Bearer".
	AuthScheme string

	// Validator is a function to validate key.
	// Optional. Default: nil
	Validator func(*fiber.Ctx, string) (bool, error)

	// Context key to store the bearertoken from the token into context.
	// Optional. Default: "token".
	ContextKey string
}

Jump to

Keyboard shortcuts

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