auth

package module
v0.0.0-...-d1c3e25 Latest Latest
Warning

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

Go to latest
Published: May 23, 2025 License: MIT Imports: 16 Imported by: 0

README

krakend-apikey-auth

HTTP Basic authentication middleware for the KrakenD-CE

Install and test

git clone https://github.com/krakend/krakend-ce.git
cd krakend-ce

#Modify executor.go
#Add to imports: 
# apikeyauth "github.com/anshulgoel27/krakend-apikey-auth"
# apikeyauthgin "github.com/anshulgoel27/krakend-apikey-auth/gin"
#Add to NewCmdExecutor (before "handlerF := e.HandlerFactory.NewHandlerFactory"):
# apiKeyAuthManager, err := apikeyauthgin.NewApiKeyAuthenticator(cfg, logger)
# if err != nil {
#	logger.Warning("[SERVICE: apikey-auth]", err.Error())
# }
#Update signature of function "NewHandlerFactory" to accept apiKeyAuthManager as parameter
#Modify handler_factory.go
#Add to imports: 
# apikeyauth "github.com/anshulgoel27/krakend-apikey-auth"
# apikeyauthgin "github.com/anshulgoel27/krakend-apikey-auth/gin"
#Update function NewHandlerFactory to accept apiKeyAuthManager as parameter
#Add to NewHandlerFactory (before "return handlerFactory"):
# if apiKeyAuthManager != nil {
#	handlerFactory = apikeyauthgin.NewHandlerFactory(apiKeyAuthManager, handlerFactory, logger)
# }

go get github.com/anshulgoel27/krakend-apikey-auth/gin

make build

./krakend run -c ./krakend.json -d

curl -i -H'Authorization: Bearer 58427514-be32-0b52-b7c6-d01fada30497' http://localhost:8080/adminonly/test

Example krakend.json

{
    "version": 3,
    "name": "My lovely gateway",
    "port": 8080,
    "cache_ttl": 3600,
    "timeout": "3s",
    "extra_config": {
        "github_com/anshulgoel27/krakend-apikey-auth": {
            "strategy": "header",
            "identifier": "Authorization",
            "keys": [
                {
                    "@plain": "4d2c61e1-34c4-e96c-9456-15bd983c5019",
                    "key": "a6a6d530a77a28fad2359223759d2d2231b516a31de2c09ad046726610f0fd87",
                    "roles": [
                        "user"
                    ],
                    "@description": "ACME Inc."
                },
                {
                    "@plain": "58427514-be32-0b52-b7c6-d01fada30497",
                    "key": "0d85b6ef02794cbf3fef4506286aaba2d499b1f825a5452d9f3444d50b33b48c",
                    "roles": [
                        "admin"
                    ],
                    "@description": "Administrators Inc."
                }
            ]
        }
    },
    "endpoints": [
        {
            "endpoint": "/adminonly/{user}",
            "method": "GET",
            "headers_to_pass": [
                "Authorization",
                "Content-Type"
            ],
            "backend": [
                {
                    "host": [
                        "https://api.github.com"
                    ],
                    "url_pattern": "/",
                    "whitelist": [
                        "authorizations_url",
                        "code_search_url"
                    ]
                }
            ],
            "extra_config": {
                "github_com/anshulgoel27/krakend-apikey-auth": {
                    "roles": [
                        "admin"
                    ]
                }
            }
        },
        {
            "endpoint": "/both/{user}",
            "method": "GET",
            "headers_to_pass": [
                "Authorization",
                "Content-Type"
            ],
            "backend": [
                {
                    "host": [
                        "https://api.github.com"
                    ],
                    "url_pattern": "/",
                    "whitelist": [
                        "authorizations_url",
                        "code_search_url"
                    ]
                }
            ],
            "extra_config": {
                "github_com/anshulgoel27/krakend-apikey-auth": {
                    "roles": [
                        "admin",
                        "user"
                    ]
                }
            }
        }
    ]
}

Documentation

Index

Constants

View Source
const (
	AuthorizationHeader = "Authorization"
	AuthorizationBearer = "Bearer "
	AuthorizationBasic  = "Basic "
	UserIdHeader        = "X-User-Id"
	UserEmailHeader     = "X-User-Email"
	OrgIdHeader         = "X-Org-Id"
	OrgNameHeader       = "X-Org-Name"
)
View Source
const Namespace = "github_com/anshulgoel27/krakend-apikey-auth"

Namespace is the key to look for extra configuration details

Variables

View Source
var ErrNoConfig = errors.New("no config defined for the module")

Functions

func FetchAllKeys

func FetchAllKeys(health_endpoint string, keys_endpoint string, l logging.Logger,
	logPrefix string, authManager *AuthKeyLookupManager)

func StartConsumer

func StartConsumer(ctx context.Context, l logging.Logger, logPrefix string, authManager *AuthKeyLookupManager)

Types

type ApiKey

type ApiKey struct {
	Key             string                 `json:"key"`
	Roles           []string               `json:"roles"`           // Roles as a slice
	ExpirationDate  time.Time              `json:"expiration_date"` // Expiration date for API key
	CreationDate    time.Time              `json:"creation_date"`   // Creation date for API key
	UserId          string                 `json:"user_id"`
	UserEmail       string                 `json:"user_email"`
	OrgID           string                 `json:"org_id"`
	OrgName         string                 `json:"org_name"`
	Enabled         bool                   `json:"enabled"`
	RoleMap         map[string]struct{}    `json:"-"` // RoleMap for fast lookup
	AdditionalProps map[string]interface{} `json:"-"`
}

ApiKey structure with a persistent role map

type ApiKeyStrategy

type ApiKeyStrategy string

Define enum for Strategy

const (
	Header      ApiKeyStrategy = "header"
	QueryString ApiKeyStrategy = "query_string"
)

type AuthFunc

type AuthFunc func(apiKeyLookupManager *AuthKeyLookupManager, r *http.Request) (bool, error)

func NewApiKeyAuthenticator

func NewApiKeyAuthenticator(cfg EndpointApiKeyConfig) AuthFunc

type AuthKeyLookupManager

type AuthKeyLookupManager struct {
	// contains filtered or unexported fields
}

AuthKeyLookupManager class with added role-based lookup

func NewAuthKeyLookupManager

func NewAuthKeyLookupManager(config ServiceApiKeyConfig) *AuthKeyLookupManager

Constructor for LookupManager

func (*AuthKeyLookupManager) DefaultIdentifier

func (manager *AuthKeyLookupManager) DefaultIdentifier() string

func (*AuthKeyLookupManager) DefautlStrategy

func (manager *AuthKeyLookupManager) DefautlStrategy() ApiKeyStrategy

func (*AuthKeyLookupManager) PropagateRoleHeader

func (manager *AuthKeyLookupManager) PropagateRoleHeader() string

func (*AuthKeyLookupManager) ValidateKeyAndRole

func (manager *AuthKeyLookupManager) ValidateKeyAndRole(key string, role string) (bool, error)

Method to validate if the key and role are valid

func (*AuthKeyLookupManager) ValidateKeyAndRoles

func (manager *AuthKeyLookupManager) ValidateKeyAndRoles(key string, roles []string) (bool, string, ApiKey, error)

Method to validate if the key and any role from the list are valid

type CreatedEvent

type CreatedEvent struct {
	Keys []CreatedKeyData `json:"keys"`
}

type CreatedKeyData

type CreatedKeyData struct {
	UserID         string    `json:"user_id"`
	OrgID          string    `json:"org_id"`
	OrgName        string    `json:"org_name"`
	Key            string    `json:"hashed_key"`
	Email          string    `json:"org_email"`
	ExpirationDate time.Time `json:"expiration_date"`
	CreationDate   time.Time `json:"creation_date"`
	Enabled        bool      `json:"enabled"`
	Plan           string    `json:"plan_name"`
	KeyLabel       string    `json:"key_label"`
}

Data structure for CREATED messages

type DeleteEvent

type DeleteEvent struct {
	Keys []DeletedKeyData `json:"keys"`
}

type DeletedKeyData

type DeletedKeyData struct {
	Key string `json:"hashed_key"`
}

Data structure for DELETED messages

type EndpointApiKeyConfig

type EndpointApiKeyConfig struct {
	Roles []string `json:"roles,omitempty"`
	// The header name or the query string name that contains the API key. Defaults to key when using the query_string strategy and to Authorization when using the header strategy. The identifier set here is used across all endpoints with API key authentication enabled, but they can override this entry individually.
	// Examples: "Authorization" , "X-Key"
	// Defaults to "Authorization"
	Identifier string `json:"identifier,omitempty"`
	// Specifies where to expect the user API key, whether inside a header or as part of the query string. The strategy set here is used across all endpoints with API key authentication enabled, but they can override this entry individually.
	// Possible values are: "header" , "query_string"
	// Defaults to "header"
	Strategy ApiKeyStrategy `json:"strategy,omitempty"`
}

func ParseEndpointConfig

func ParseEndpointConfig(apiKeyLookupManager *AuthKeyLookupManager, cfg config.ExtraConfig) (EndpointApiKeyConfig, error)

func (*EndpointApiKeyConfig) Authenticate

func (d *EndpointApiKeyConfig) Authenticate(apiKeyLookupManager *AuthKeyLookupManager, r *http.Request) (bool, error)

type KeyAdminMessage

type KeyAdminMessage struct {
	Type MessageType            `json:"message_type"`
	Data map[string]interface{} `json:"data"`
}

type MessageType

type MessageType string

Define a custom type for the enum

const (
	Created MessageType = "CREATED"
	Deleted MessageType = "DELETED"
	Updated MessageType = "UPDATED"
)

Define constants for the allowed values

func (MessageType) IsValid

func (mt MessageType) IsValid() bool

Validate the Type field

type ServiceApiKeyConfig

type ServiceApiKeyConfig struct {
	// The header name or the query string name that contains the API key. Defaults to key when using the query_string strategy and to Authorization when using the header strategy. The identifier set here is used across all endpoints with API key authentication enabled, but they can override this entry individually.
	// Examples: "Authorization" , "X-Key"
	// Defaults to "Authorization"
	Identifier string `json:"identifier,omitempty"`
	// Specifies where to expect the user API key, whether inside a header or as part of the query string. The strategy set here is used across all endpoints with API key authentication enabled, but they can override this entry individually.
	// Possible values are: "header" , "query_string"
	// Defaults to "header"
	Strategy ApiKeyStrategy `json:"strategy,omitempty"`
	// The name of a header that will propagate to the backend containing the matching role.
	// The backend receives no header when the string is empty, or the attribute is not declared.
	// Otherwise, the backend receives the declared header name containing the first matching role of the user.
	// The header value will be ANY when the endpoint does not require roles. For instance, if an API key has roles [A, B],
	// and the endpoint demands roles [B, C], the backend will receive a header with the value B.
	// Default X-API-Role
	PropagateRole string   `json:"propagate_role,omitempty"`
	Keys          []ApiKey `json:"keys"`
	AdminKeyEnv   string   `json:"admin_key_env"`
}

ServiceApiKeyConfig structure remains unchanged

func ParseServiceConfig

func ParseServiceConfig(cfg config.ExtraConfig) (ServiceApiKeyConfig, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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