authecho

package module
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2023 License: MIT Imports: 16 Imported by: 1

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.

go get 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

This section is empty.

Functions

func CodeToken added in v0.3.0

func CodeToken(c echo.Context, code, cookieName string, redirect *RedirectSetting, sessionStore *sessions.FilesystemStore) error

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 added in v0.2.2

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 added in v0.2.0

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

MiddlewareRole that checks the role claim. This middleware just work with *claims.Custom claims.

func MiddlewareScope added in v0.2.0

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

MiddlewareScope that checks the scope claim. This middleware just work with *claims.Custom 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].

func RedirectURI added in v0.3.0

func RedirectURI(r *http.Request, callback, baseURL, schema string) (string, error)

func RefreshToken added in v0.3.0

func RefreshToken(c echo.Context, refreshToken, cookieName string, oldCookieValue string, redirect *RedirectSetting, sessionStore *sessions.FilesystemStore) (*store.Token, error)

RefreshToken refreshes the access token and set the cookie.

func RemoveAuthQueryParams added in v0.3.0

func RemoveAuthQueryParams(r *http.Request)

func SaveRedirectQueryParams added in v0.3.0

func SaveRedirectQueryParams(c echo.Context, cookieName string, redirect *RedirectSetting, sessionStore store.SessionStore)

func SetRedirectQueryParams added in v0.3.0

func SetRedirectQueryParams(c echo.Context, cookieName string, redirect *RedirectSetting, sessionStore store.SessionStore)

Types

type ClaimsHeader added in v0.3.2

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"`
}

func (ClaimsHeader) SetHeaders added in v0.3.2

func (h ClaimsHeader) SetHeaders(c echo.Context)

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 WithClaimsHeader added in v0.3.2

func WithClaimsHeader(claimsHeader *ClaimsHeader) Option

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 added in v0.2.1

func WithNoop(noop bool) Option

func WithParserFunc added in v0.4.8

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

func WithRedirect added in v0.2.1

func WithRedirect(redirect *RedirectSetting) Option

func WithSkipper

func WithSkipper(skipper middleware.Skipper) Option

type OptionRole added in v0.3.2

type OptionRole func(*optionsRole)

func WithMethodsRole added in v0.3.2

func WithMethodsRole(methods ...string) OptionRole

WithMethods sets the methods to check.

func WithNoopRole added in v0.4.0

func WithNoopRole(v bool) OptionRole

WithNoopRole sets the noop option.

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

func WithRoles added in v0.3.2

func WithRoles(roles ...string) OptionRole

WithRoles sets the roles to check.

type OptionScope added in v0.3.2

type OptionScope func(*optionsScope)

func WithMethodsScope added in v0.3.2

func WithMethodsScope(methods ...string) OptionScope

WithMethods sets the methods to check.

func WithNoopScope added in v0.4.0

func WithNoopScope(v bool) OptionScope

WithNoopScope sets the noop option.

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

func WithScopes added in v0.3.2

func WithScopes(scopes ...string) OptionScope

WithRoles sets the roles to check.

type OptionSkipper added in v0.4.0

type OptionSkipper func(*optionsSkipper)

func WithSkipAll added in v0.4.0

func WithSkipAll(v bool) OptionSkipper

WithSkipAll sets skipAll to true and disable the check token.

func WithSuffixes added in v0.4.0

func WithSuffixes(suffixes ...string) OptionSkipper

WithSuffixes sets the suffixes to skip.

type RedirectSetting added in v0.2.1

type RedirectSetting struct {
	AuthURL      string   `cfg:"-"`
	TokenURL     string   `cfg:"-"`
	ClientID     string   `cfg:"-"`
	ClientSecret string   `cfg:"-"`
	Scopes       []string `cfg:"-"`

	// CookieName is the name of the cookie. Default is "auth_" + ClientID.
	CookieName string `cfg:"cookie_name"`
	// MaxAge the number of seconds until the cookie expires.
	MaxAge int `cfg:"max_age"`
	// Path that must exist in the requested URL for the browser to send the Cookie header.
	Path string `cfg:"path"`
	// Domain for defines the host to which the cookie will be sent.
	Domain string `cfg:"domain"`
	// Secure to cookie only sent over HTTPS.
	Secure bool `cfg:"secure"`
	// SameSite for Lax 2, Strict 3, None 4.
	SameSite http.SameSite `cfg:"same_site"`
	// HttpOnly for true for not accessible by JavaScript.
	HttpOnly bool `cfg:"http_only"`

	// NoClientIDParam is use to not add client_id in the query params.
	NoClientIDParam bool `cfg:"no_client_id_param"`
	// Callback is the callback URI.
	Callback string `cfg:"callback"`
	// 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"`

	// 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"`
}

func (*RedirectSetting) MapConfigCookie added in v0.4.1

func (r *RedirectSetting) MapConfigCookie() store.Config

Jump to

Keyboard shortcuts

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