authecho

package
v0.7.7 Latest Latest
Warning

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

Go to latest
Published: Jan 19, 2024 License: MIT Imports: 19 Imported by: 6

README

auth library for echo

This library provides a middleware for echo web-framework to handle authentication.
Features are auto-redirection to login page, auto-refresh of access token.

There are a few other middlewares in it that can help you to build a complete authentication system.

import "github.com/worldline-go/auth/middlewares/authecho"

Usage

It is working based on the jwks functions. Our auth library already return a jwks key function.

// set a noop value to disable authentication in test mode
noop := strings.EqualFold(os.Getenv("ENV"), "test")
// or you can set the "noop" to value of active auth provider
// providerConfig.Active = "noop"

// jwks part by auth library
provider := providerConfig.ActiveProvider(auth.WithNoop(noop))

// jwks key function
jwks, err := provider.JWTKeyFunc(ctx)
if err != nil {
    return err
}

// close jwks retantion in background
defer jwks.EndBackground()

// echo part

// if we want to use the middleware for all routes
// e.Use(authecho.MiddlewareJWT(
//     // if your jwks from a noop provider, noop always true
//     // authecho.WithNoop(noop),
//     authecho.WithKeyFunc(jwks.Keyfunc),
//     authecho.WithSkipper(authecho.NewSkipper()),
// ))

// if we want to use the middleware for some routes
// add this to the parameters of the route
mJWT := authecho.MiddlewareJWT(
    // if your jwks from a noop provider, noop always true
    // authecho.WithNoop(noop),
    authecho.WithKeyFunc(jwks.Keyfunc),
    authecho.WithSkipper(authecho.NewSkipper()),
)

// control based on roles and scopes
// it will check transaction role and email scope, if not exist it will return 403
e.GET("/", func(c echo.Context) error {
    //...
}, authecho.MiddlewareRole(
        // if your jwks from a noop provider, noop always true
        // authecho.WithNoopRole(noop),
        authecho.WithRoles("transaction"),
    ),
    authecho.MiddlewareScope(
        // if your jwks from a noop provider, noop always true
        // authecho.WithNoopRole(noop),
        authecho.WithScopes("email"),
    ),
)

Options

WithNoop return a new noop function, it is useful when you want to disable the middleware for some routes.

This is the same effect to set Active value in config to noop.

authecho.WithNoop(noop bool)

WithKeyFunc return a new key function, it is required to use the jwks key function.

authecho.WithKeyFunc(fn jwt.Keyfunc)

WithSkipper return a new skipper function, it is useful when you want to skip the middleware for some routes.

authecho WithSkipper(skipper middleware.Skipper)

// Example:
// NewSkipper ask for a list of suffexes to skip the middleware
authecho.WithSkipper(authecho.NewSkipper())

WithClaims return a new claims function, it is useful when you want to add custom claims to the token.
We have already a custom claims function for the auth library.
Don't use it, if you don't know what you are doing.

authecho.WithClaims(newClaims func() jwt.Claims)

WithClaimsHeader to add custom claims to the header of the request. Set the header-key for scopes, roles and user.

type ClaimsHeader struct {
	// Scopes is the header name for scopes, default is X-Auth-Scopes.
	Scopes string `cfg:"scopes"`
	// Roles is the header name for roles, default is X-Auth-Roles.
	Roles string `cfg:"roles"`
	// User is the header name for user, default is X-Auth-User.
	User string `cfg:"user"`
	// Custom is the header name for custom claims.
	Custom map[string]string `cfg:"custom"`
}

// Example for custom, it will get key from the token and set it to the header.
custom := map[string]string{
    "X-Auth-Username": "name",
    "X-Auth-Useremail": "email",
}
WithClaimsHeader(claimsHeader *ClaimsHeader)

WithRedirect to add custom redirect settings.
Redirect to the login page if the user is not authenticated.
Checking the Authorization header for the token, if not exist checking the cookie.

Before to authenticate with access_token, we check the refresh_token, default is 10s before the access_token expires.

RedirectSetting struct:

// CookieName is the name of the cookie. Default is "auth_" + ClientID.
CookieName string `cfg:"cookie_name"`
// Callback is the callback URI.
Callback string `cfg:"callback"`
// MaxAge for the cookie.
MaxAge int `cfg:"max_age"`
// Path for the cookie.
Path string `cfg:"path"`
// Domain for the cookie.
Domain string `cfg:"domain"`
// BaseURL is the base URL to use for the redirect.
// Default is the request Host with checking the X-Forwarded-Host header.
BaseURL string `cfg:"base_url"`
// Schema is the default schema to use for the redirect if no schema is provided.
// Default is the https schema.
Schema string `cfg:"schema"`
// Secure is the secure flag for the cookie.
Secure bool `cfg:"secure"`

// UseSession is use session instead of cookie.
UseSession bool `cfg:"use_session"`
// SessionKey secret key for session.
SessionKey string `cfg:"session_key"`

// TokenHeader to add token to header.
TokenHeader bool `cfg:"token_header"`
// RefreshToken is use to refresh the token.
RefreshToken bool `cfg:"refresh_token"`

CheckValue string `cfg:"check_value"`
CheckAgent bool   `cfg:"check_agent"`

If you not give the RedirectSetting, the middleware will not redirect to the login page.

WithRedirect(redirect *RedirectSetting)

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// KeyClaims hold parsed claims in the echo context.
	//
	// Default claims is *claims.Custom.
	KeyClaims = "claims"
	// KeyToken hold parsed *jwt.Token in the echo context.
	//
	// This is default key for echo-jwt's ContextKey if not set.
	KeyToken = "token"
	// KeyAccessToken hold the access token in the echo context.
	KeyAccessToken = "access_token"
	// KeySkipper is true if the jwt middleware skipped.
	KeySkipper = "skipped"

	// KeyAuthNoop hold true if the provider is noop.
	KeyAuthNoop       = "auth_noop"
	KeyAuthIntrospect = "auth_introspect"

	// KeyAuthError internal error for code token get, str format.
	KeyAuthError = "auth_error"

	KeyClearCookieOnJWTKIDError = "clear_cookie_on_jwt_kid_error"
	// KeyDisableRedirect is true if the redirection is disabled.
	KeyDisableRedirect = "disable_redirect"
	// KeyDisableRedirectWithCookie is true redirection disabled and removed cookie.
	KeyDisableRedirectWithCookie = "disable_redirect_with_cookie"
)
View Source
var DisableControlCheckKey = "auth_disable_control_check"
View Source
var DisableRoleCheckKey = "auth_disable_role_check"
View Source
var DisableScopeCheckKey = "auth_disable_scope_check"
View Source
var Store = authStore{
	// contains filtered or unexported fields
}

Functions

func MiddlewareControl added in v0.7.3

func MiddlewareControl[T any](fn func(c echo.Context, claim T) error, opts ...OptionControl) echo.MiddlewareFunc

MiddlewareControl that checks the claim manually with a function.

func MiddlewareJWT

func MiddlewareJWT(opts ...Option) echo.MiddlewareFunc

MiddlewareJWT returns a JWT middleware. Default claims is *claims.Custom.

WithRedirect option not usable in this function.

func MiddlewareJWTWithRedirection

func MiddlewareJWTWithRedirection(opts ...Option) []echo.MiddlewareFunc

MiddlewareJWTWithRedirection returns a JWT middleware with usable redirection option. Default claims is *claims.Custom.

Redirection returns 2 middleware functions.

func MiddlewareRole

func MiddlewareRole(opts ...OptionRole) echo.MiddlewareFunc

MiddlewareRole that checks the role claim.

This middleware just work with ClaimsRole interface in claim.

func MiddlewareScope

func MiddlewareScope(opts ...OptionScope) echo.MiddlewareFunc

MiddlewareScope that checks the scope claim.

This middleware just work with ClaimsScope interface in claims.

func NewSkipper

func NewSkipper(opts ...OptionSkipper) middleware.Skipper

NewSkipper returns a new Skipper that skips the given suffixes.

Set skip is true to skip all.

Default suffixes are: [/ping, /health, /metrics].

Types

type ClaimsRole added in v0.7.0

type ClaimsRole interface {
	HasRole(role string) bool
}

type ClaimsScope added in v0.7.0

type ClaimsScope interface {
	HasScope(scope string) bool
}

type Option

type Option func(*options)

func WithClaims

func WithClaims(newClaims func() jwt.Claims) Option

WithClaims sets the claims to use, function must return a pointer.

func WithConfig

func WithConfig(cfg echojwt.Config) Option

WithConfig sets the config to use

Don't use if you don't know what you are doing.

func WithKeyFunc

func WithKeyFunc(fn jwt.Keyfunc) Option

func WithNoop

func WithNoop(noop bool) Option

func WithParserFunc

func WithParserFunc(fn func(tokenString string, claims jwt.Claims) (*jwt.Token, error)) Option

func WithRedirect

func WithRedirect(redirectSetting *redirect.Setting) Option

func WithSkipper

func WithSkipper(skipper middleware.Skipper) Option

type OptionControl added in v0.7.3

type OptionControl func(*optionsControl)

func WithNoopControl added in v0.7.3

func WithNoopControl(v bool) OptionControl

WithNoopControl sets the noop option.

If provider already has a noop, this one will be ignored.

type OptionRole

type OptionRole func(*optionsRole)

func WithMethodsRole

func WithMethodsRole(methods ...string) OptionRole

WithMethods sets the methods to check.

func WithNoopRole

func WithNoopRole(v bool) OptionRole

WithNoopRole sets the noop option.

If provider already has a noop, this one will be ignored.

func WithRoles

func WithRoles(roles ...string) OptionRole

WithRoles sets the roles to check.

type OptionScope

type OptionScope func(*optionsScope)

func WithMethodsScope

func WithMethodsScope(methods ...string) OptionScope

WithMethods sets the methods to check.

func WithNoopScope

func WithNoopScope(v bool) OptionScope

WithNoopScope sets the noop option.

If provider already has a noop, this one will be ignored.

func WithScopes

func WithScopes(scopes ...string) OptionScope

WithRoles sets the roles to check.

type OptionSkipper

type OptionSkipper func(*optionsSkipper)

func WithSkipAll

func WithSkipAll(v bool) OptionSkipper

WithSkipAll sets skipAll to true and disable the check token.

func WithSuffixes

func WithSuffixes(suffixes ...string) OptionSkipper

WithSuffixes sets the suffixes to skip.

Jump to

Keyboard shortcuts

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