httpmiddleware

package
v2.33.17 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2023 License: MIT Imports: 20 Imported by: 0

README

Migration

Migration from 1.* to 2.*

  • CorsMiddleware

    The old CorsMiddlewareV2 is now replaced by CorsMiddleware

    Migration steps:

    • If you are using CorsMiddlewareV2, change it to CorsMiddleware

    • If you are using CorsMiddleware, add this code to the endpoints that need CORS, remember to configure it to your needs.

      server.mux.
      	HandleFunc("<path>", http_middleware.Options(
      		[]string{http.MethodGet},
      		[]string{http_model.HeaderContentType},
      	)).
      	Methods(http.MethodOptions)
      
  • AuthenticateMiddleware

    The old AuthenticateMiddleware has been modified to take care of retrieving User ID by itself.

    Migration steps:

    • Add the following code to your main file.
      http_middleware.Configure(
          http_middleware.Config{Stage: authenticateStage},
      )
      

Documentation

Overview

Package httpmiddleware contains middleware for REST API's built with Gorilla web toolkit (router) and OpenCensus (telemetry).

The package is using on "github.com/gorilla/mux" "go.opencensus.io/trace"

Examples

An example including creating a router, adding a route and security as well as all middleware.

router := mux.NewRouter()

const pathToCreateCompanyUser = "/companies/{companyID:[a-zA-Z0-9-]+}/users"
router.
    HandleFunc(pathToCreateUser, http_middleware.ContentType(
        server.createCompanyUserHandler, http_model.MimeJSON,
    )).
    Methods(http.MethodPost)

router.
    HandleFunc(pathToCreateUser, http_middleware.Options(
        []string{http.MethodPost},
        []string{http_model.HeaderContentType},
    )).
    Methods(http.MethodOptions)

http_middleware.
    HandleSecureEndpoint(pathToCreateCompanyUser).
    Methods(http.MethodPost).
    AccessToken().
    Authorize(ActionIAMCreateUser, http_middleware.NilResourceFunc).
    Authorize(ActionIAMInviteUser, companyOriginFromPathFunc)

router.Use(
    // Middleware is run from top to bottom, order is important
    http_middleware.TrailingSlashMiddleware,
    http_middleware.CorsMiddleware,
    http_middleware.OpenCensusMiddleware,
    http_middleware.AuthenticateMiddleware("<jwkeyset_url>"),
    http_middleware.AuthorizeMiddleware(authorizerClient),
)

Index

Constants

View Source
const (
	HeaderAuthorization = "Authorization"
)

Variables

View Source
var NilResourceFunc = func(req *http.Request) (*common.Origin, error) {
	return nil, nil
}

NilResourceFunc represents the Zero Value ResourceFunc.

Functions

func AuthenticateMiddleware

func AuthenticateMiddleware(keySetURL string) mux.MiddlewareFunc

AuthenticateMiddleware retrieves the security configuration for the matched route and handles Access Token validation and stores the token claims in the request context. Deprecated: Use AuthenticateMiddlewareV3() instead

func AuthenticateMiddlewareV3 added in v2.1.1

func AuthenticateMiddlewareV3() mux.MiddlewareFunc

AuthenticateMiddlewareV3 retrieves the security configuration for the matched route and handles Access Token validation and stores the token claims in the request context.

func AuthorizeMiddleware

func AuthorizeMiddleware(authorizer Authorizer) mux.MiddlewareFunc

AuthorizeMiddleware retrieves the security configuration for the matched route and handles the configured authorizations. If any of the configured ResourceFuncs returns a HTTPError or an error wrapping a HTTPError, the error code and message from that error is written. Other errors from the ResourceFuncs results in a http.StatusInternalServerError response being written. If the request fails the authorization check, http.StatusUnauthorized is returned to the client.

func Configure

func Configure(conf Config)

func ContentType

func ContentType(next http.HandlerFunc, contentTypes ...string) http.HandlerFunc

ContentType wraps a HandlerFunc and checks the incoming content-type with a list of allowed content types.

func CorsMiddleware

func CorsMiddleware(next http.Handler) http.Handler

CorsMiddleware adds Access-Control-Allow-Origin header to responses.

func GetInternalServerErrorResponseBody added in v2.13.0

func GetInternalServerErrorResponseBody(defaultResponse []byte, secConfig SecurityConfig) []byte

func GetUnauthenticedErrorResponseBody added in v2.13.0

func GetUnauthenticedErrorResponseBody(defaultResponse []byte, secConfig SecurityConfig) []byte

func GetUnauthorizedErrorResponseBody added in v2.13.0

func GetUnauthorizedErrorResponseBody(defaultResponse []byte, secConfig SecurityConfig) []byte

func OpenCensusMiddleware

func OpenCensusMiddleware(next http.Handler) http.Handler

OpenCensusMiddleware adds request method and path template as span name.

func Options

func Options(methods, headers []string) http.HandlerFunc

Options takes a list of methods and headers and returns an Options HandlerFunc

func Recovery

func Recovery(next http.Handler) http.Handler

func TrailingSlashMiddleware

func TrailingSlashMiddleware(next http.Handler) http.Handler

TrailingSlashMiddleware removes trailing slash from URL's

Types

type Authorizer

type Authorizer interface {
	IsAuthorizedWithContext(ctx context.Context, userID, action string, resource *common.Origin) (bool, error)
}

type Config

type Config struct {
	Stage string

	// Configures the usage of a User ID Cache when using an Access Token
	UseUserIDCache bool

	// This parameter is deprecated.
	Client interface{}
}

type ResourceFunc

type ResourceFunc func(*http.Request) (*common.Origin, error)

ResourceFunc takes a *http.Request and returns the resource to use for authorization. If the ResourceFunc fails because of invalid input data or a missing resource, return a HttpError, or an error wrapping a HTTPError. The following example ResourceFunc expects an input struct with a non-empty field

func fieldFromBodyFunc(r *http.Request) (*common.Origin, error) {
    var inputData struct {
        field string `json:"field,omitempty"`
    }
    body, err := ioutil.ReadAll(r.Body)
    if err != nil {
        return nil, err
    }
    r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
    if err := json.Unmarshal(body, &inputData); err != nil {
        return nil, &http_model.HTTPError{
            Msg:        "Failed to unmarshal body",
            StatusCode: http.StatusBadRequest,
        }
    }
    if inputData.field == "" || uuid.UUID(inputData.field) == uuid.EmptyUUID {
        return nil, &http_model.HTTPError{
            Msg:        "Required field 'field' is empty",
            StatusCode: http.StatusBadRequest,
        }
    }
    return &common.Origin{Id: inputData.field, Type: "example"}, nil
}

type ResponseConfig added in v2.13.0

type ResponseConfig interface {
	InternalErrorResponse() []byte
	UnauthenticateResponse() []byte
	UnauthorizedResponse() []byte
}

type SecurityConfig

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

SecurityConfig represents how to authenticate and authorize a given endpoint and method.

func HandleSecureEndpoint

func HandleSecureEndpoint(endpoint string) *SecurityConfig

HandleSecureEndpoint creates a new SecurityConfig for the specified endpoint.

func HandleSecureEndpointCustomErrorResponse added in v2.13.0

func HandleSecureEndpointCustomErrorResponse(endpoint string, responses ResponseConfig) *SecurityConfig

func (*SecurityConfig) AccessToken

func (s *SecurityConfig) AccessToken(headers ...string) *SecurityConfig

AccessToken adds Access Token as a mean for Authentication to the SecurityConfig. The header defaults to "Authorization".

func (*SecurityConfig) Authorize

func (s *SecurityConfig) Authorize(action string, resourceFunc ResourceFunc) *SecurityConfig

Authorize adds an Authorization Configuration to the SecurityConfig.

func (*SecurityConfig) Methods

func (s *SecurityConfig) Methods(methods ...string) *SecurityConfig

Methods adds methods to the SecurityConfig.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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