Documentation ¶
Index ¶
- Constants
- func GetAccessToken(ctx *context.Context) string
- func GetUser[T User](ctx *context.Context) T
- type Auth
- func (s *Auth[T]) AddProvider(providers ...Provider[T]) *Auth[T]
- func (s *Auth[T]) GetUser(ctx *context.Context) T
- func (s *Auth[T]) Refresh(ctx stdContext.Context, refreshToken []byte) ([]byte, []byte, error)
- func (s *Auth[T]) RefreshHandler(ctx *context.Context)
- func (s *Auth[T]) SetErrorHandler(errHandler ErrorHandler) *Auth[T]
- func (s *Auth[T]) SetTransformer(transformer Transformer[T]) *Auth[T]
- func (s *Auth[T]) SetTransformerFunc(transfermerFunc func(ctx stdContext.Context, tok *VerifiedToken) (T, error)) *Auth[T]
- func (s *Auth[T]) Signin(ctx stdContext.Context, username, password string) ([]byte, []byte, error)
- func (s *Auth[T]) SigninHandler(ctx *context.Context)
- func (s *Auth[T]) Signout(ctx stdContext.Context, token []byte, all bool) error
- func (s *Auth[T]) SignoutAllHandler(ctx *context.Context)
- func (s *Auth[T]) SignoutHandler(ctx *context.Context)
- func (s *Auth[T]) Verify(ctx stdContext.Context, token []byte, verifyFuncs ...VerifyUserFunc[T]) (T, StandardClaims, error)
- func (s *Auth[T]) VerifyHandler(verifyFuncs ...VerifyUserFunc[T]) context.Handler
- func (s *Auth[T]) WithProviderAndErrorHandler(provider Provider[T], errHandler ErrorHandler) *Auth[T]
- type ClaimsProvider
- type Configuration
- type CookieConfiguration
- type DefaultErrorHandler
- type ErrorHandler
- type Provider
- type RefreshRequest
- type SigninRequest
- type SigninResponse
- type StandardClaims
- type Transformer
- type TransformerFunc
- type User
- type VerifiedToken
- type VerifyUserFunc
Constants ¶
const ( // The JWT Key ID for access tokens. KIDAccess = "IRIS_AUTH_ACCESS" // The JWT Key ID for refresh tokens. KIDRefresh = "IRIS_AUTH_REFRESH" )
Variables ¶
This section is empty.
Functions ¶
func GetAccessToken ¶
GetAccessToken accepts the iris Context and returns the raw access token value. It's only available after Auth.VerifyHandler is executed.
Types ¶
type Auth ¶
type Auth[T User] struct { // contains filtered or unexported fields }
Auth holds the necessary functionality to authorize and optionally authenticating users to access and perform actions against the resource server (Iris API). It completes a secure and fast JSON Web Token signer and verifier which, based on the custom application needs, can be further customized. Each Auth of T instance can sign and verify a single custom <T> instance, more Auth instances can share the same configuration to support multiple custom user types. Initialize a new Auth of T instance using the New or MustLoad package-level functions. Most important methods of the instance are: - AddProvider - SigninHandler - VerifyHandler - SignoutHandler - SignoutAllHandler
Example can be found at: https://github.com/kataras/iris/tree/master/_examples/auth/auth/main.go.
func Must ¶
Must is a helper that wraps a call to a function returning (*Auth[T], error) and panics if the error is non-nil. It is intended for use in variable initializations such as
var s = auth.Must(auth.New[MyUser](config))
func MustLoad ¶
MustLoad binds a filename (fullpath) configuration yaml or json and constructs a new Auth instance. It panics on error.
func New ¶
func New[T User](config Configuration) (*Auth[T], error)
New initializes a new Auth instance typeof T and returns it. The T generic can be any custom struct. It accepts a Configuration value which can be constructed manually or through a configuration file using the MustGenerateConfiguration or MustLoadConfiguration or LoadConfiguration or MustLoad package-level functions.
Example can be found at: https://github.com/kataras/iris/tree/master/_examples/auth/auth/main.go.
func (*Auth[T]) AddProvider ¶
AddProvider registers one or more providers to this Auth of T instance and returns itself. Look the Provider godoc for more.
func (*Auth[T]) GetUser ¶
GetUser accepts the iris Context and returns the T custom user/claims struct value. It's only available after Auth.VerifyHandler is executed.
func (*Auth[T]) Refresh ¶
Refresh accepts a previously generated refresh token (from SigninHandler) and returns a new access and refresh token pair.
func (*Auth[T]) RefreshHandler ¶
RefreshHandler reads the request body which should include data for `RefreshRequest` structure and sends a new access and refresh token pair, also sets the cookie to the new encrypted access token value. See `Refresh` method for more.
func (*Auth[T]) SetErrorHandler ¶
func (s *Auth[T]) SetErrorHandler(errHandler ErrorHandler) *Auth[T]
SetErrorHandler sets a custom error handler to this Auth of T instance and returns itself. Look the Provider and ErrorHandler godoc for more.
func (*Auth[T]) SetTransformer ¶
func (s *Auth[T]) SetTransformer(transformer Transformer[T]) *Auth[T]
SetTransformer sets a custom transformer to this Auth of T instance and returns itself. Look the Provider and Transformer godoc for more.
func (*Auth[T]) SetTransformerFunc ¶
func (s *Auth[T]) SetTransformerFunc(transfermerFunc func(ctx stdContext.Context, tok *VerifiedToken) (T, error)) *Auth[T]
SetTransformerFunc like SetTransformer method but accepts a function instead.
func (*Auth[T]) Signin ¶
Signin signs a token based on the provided username and password and returns a pair of access and refresh tokens.
Signin calls the Provider.Signin method to check if a user is authenticated by the given username and password combination.
func (*Auth[T]) SigninHandler ¶
SignHandler generates and sends a pair of access and refresh token to the client as JSON body of `SigninResponse` and cookie (if cookie setting was provided). See `Signin` method for more.
func (*Auth[T]) Signout ¶
Signout accepts the access token and a boolean which reports whether the signout should be applied to all tokens generated for a specific user (logout from all devices) or just the provided token's one. It calls the Provider's InvalidateToken(all=false) or InvalidateTokens (all=true).
func (*Auth[T]) SignoutAllHandler ¶
SignoutAllHandler verifies the request's access token and should invalidate all the tokens generated previously calling the Provider's InvalidateTokens method. See `Signout` method too.
func (*Auth[T]) SignoutHandler ¶
SignoutHandler verifies the request's access token and invalidates it, calling the Provider's InvalidateToken method. See `Signout` method too.
func (*Auth[T]) Verify ¶
func (s *Auth[T]) Verify(ctx stdContext.Context, token []byte, verifyFuncs ...VerifyUserFunc[T]) (T, StandardClaims, error)
Verify accepts a token and verifies it. It returns the token's custom and standard JWT claims.
func (*Auth[T]) VerifyHandler ¶
VerifyHandler verifies and sets the necessary information about the user(claims) and the verified token to the Iris Context and calls the Context's Next method. This information is available through auth.GetAccessToken, auth.GetStandardClaims and auth.GetUser[T] package-level functions.
See `Verify` method for more.
func (*Auth[T]) WithProviderAndErrorHandler ¶
func (s *Auth[T]) WithProviderAndErrorHandler(provider Provider[T], errHandler ErrorHandler) *Auth[T]
WithProviderAndErrorHandler registers a provider (if not nil) and an error handler (if not nil) and returns this "s" Auth instance. It's the same as calling AddProvider and SetErrorHandler at once. It's really useful when registering an Auth instance using the iris.Party.PartyConfigure method when a Provider of T and ErrorHandler is available through the registered Party's dependencies.
Usage Example:
api := app.Party("/api") api.EnsureStaticBindings().RegisterDependency( NewAuthProviderErrorHandler(), NewAuthCustomerProvider, auth.Must(auth.New[Customer](authConfig)).WithProviderAndErrorHandler, )
type ClaimsProvider ¶
type ClaimsProvider interface { GetAccessTokenClaims() StandardClaims GetRefreshTokenClaims(accessClaims StandardClaims) StandardClaims }
ClaimsProvider is an optional interface, which may not be used at all. If implemented by a Provider, it signs the jwt token using these claims to each of the following token types.
type Configuration ¶
type Configuration struct { // The authorization header keys that server should read the access token from. // // Defaults to: // - Authorization // - X-Authorization Headers []string `json:"headers" yaml:"Headers" toml:"Headers" ini:"Headers"` // Cookie optional configuration. // A Cookie.Name holds the access token value fully encrypted. Cookie CookieConfiguration `json:"cookie" yaml:"Cookie" toml:"Cookie" ini:"cookie"` // Keys MUST define the jwt keys configuration for access, // and optionally, for refresh tokens signing and verification. Keys jwt.KeysConfiguration `json:"keys" yaml:"Keys" toml:"Keys" ini:"keys"` }
Configuration holds the necessary information for Iris Auth & Single-Sign-On feature.
See the `New` package-level function.
func LoadConfiguration ¶
func LoadConfiguration(filename string) (c Configuration, err error)
LoadConfiguration reads a filename (fullpath) and returns a Configuration binded to the contents of the given filename. See Configuration.BindFile method too.
func MustGenerateConfiguration ¶
func MustGenerateConfiguration() (c Configuration)
MustGenerateConfiguration calls the Configuration's BindRandom method and returns the result. It panics on errors.
func MustLoadConfiguration ¶
func MustLoadConfiguration(filename string) Configuration
MustLoadConfiguration same as LoadConfiguration package-level function but it panics on error.
func (*Configuration) BindFile ¶
func (c *Configuration) BindFile(filename string) error
BindFile binds a filename (fullpath) to "c" Configuration. The file format is either JSON or YAML and it should be suffixed with .json or .yml/.yaml.
func (*Configuration) BindRandom ¶
func (c *Configuration) BindRandom() error
BindRandom binds the "c" configuration to random values for keys and cookie security. Keys will not be persisted between restarts, a more persistent storage should be considered for production applications, see BindFile method and LoadConfiguration/MustLoadConfiguration package-level functions.
func (*Configuration) ToJSON ¶
func (c *Configuration) ToJSON() ([]byte, error)
ToJSON returns the "c" Configuration's contents as raw json byte slice.
func (*Configuration) ToYAML ¶
func (c *Configuration) ToYAML() ([]byte, error)
ToYAML returns the "c" Configuration's contents as raw yaml byte slice.
type CookieConfiguration ¶
type CookieConfiguration struct { // Name defines the cookie's name. Name string `json:"cookie" yaml:"Name" toml:"Name" ini:"name"` // Secure if true then "; Secure" is appended to the Set-Cookie header. // By setting the secure to true, the web browser will prevent the // transmission of a cookie over an unencrypted channel. // // Defaults to false but it's true when the request is under iris.Context.IsSSL(). Secure bool `json:"secure" yaml:"Secure" toml:"Secure" ini:"secure"` // Hash is optional, it is used to authenticate cookie value using HMAC. // It is recommended to use a key with 32 or 64 bytes. Hash string `json:"hash" yaml:"Hash" toml:"Hash" ini:"hash"` // Block is optional, used to encrypt cookie value. // The key length must correspond to the block size // of the encryption algorithm. For AES, used by default, valid lengths are // 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256. Block string `json:"block" yaml:"Block" toml:"Block" ini:"block"` }
CookieConfiguration holds the necessary information for cookie client storage.
type DefaultErrorHandler ¶
type DefaultErrorHandler struct{}
DefaultErrorHandler is the default registered ErrorHandler which can be replaced through the Auth.SetErrorHandler method.
func (*DefaultErrorHandler) InvalidArgument ¶
func (e *DefaultErrorHandler) InvalidArgument(ctx *context.Context, err error)
InvalidArgument sends 400 (bad request) with "unable to parse body" as its message and the "err" value as its details.
func (*DefaultErrorHandler) Unauthenticated ¶
func (e *DefaultErrorHandler) Unauthenticated(ctx *context.Context, err error)
Unauthenticated sends 401 (unauthenticated) with the "err" value as its message.
type ErrorHandler ¶
type ErrorHandler interface { // InvalidArgument should handle any 400 (bad request) errors, // e.g. invalid request body. InvalidArgument(ctx *context.Context, err error) // Unauthenticated should handle any 401 (unauthenticated) errors, // e.g. user not found or invalid credentials. Unauthenticated(ctx *context.Context, err error) }
ErrorHandler is an optional interface which can be implemented by a Provider as well.
ErrorHandler is the interface which controls the HTTP errors on Auth.SigninHandler, Auth.VerifyHandler, Auth.SignoutHandler and Auth.SignoutAllHandler handelrs.
type Provider ¶
type Provider[T User] interface { // Signin accepts a username (or email) and a password and should // return a valid T value or an error describing // the user authentication or verification reason of failure. // // The first input argument standard context can be // casted to iris.Context if executed through Auth.SigninHandler. // // It's called on Auth.SigninHandler. Signin(ctx stdContext.Context, username, password string) (T, error) // ValidateToken accepts the standard JWT claims and the T value obtained // by the Signin method and should return a nil error on validation success // or a non-nil error for validation failure. // It is mostly used to perform checks of the T value's struct fields or // the standard claim's (e.g. origin jwt token id). // It can be an empty method too which returns a nil error. // // The first input argument standard context can be // casted to iris.Context if executed through Auth.VerifyHandler. // // It's caleld on Auth.VerifyHandler. ValidateToken(ctx stdContext.Context, standardClaims StandardClaims, t T) error // InvalidateToken is optional and can be used to allow tokens to be invalidated // from server-side. Commonly, implement when a token and user pair is saved // on a persistence storage and server can decide which token is valid or invalid. // It can be an empty method too which returns a nil error. // // The first input argument standard context can be // casted to iris.Context if executed through Auth.SignoutHandler. // // It's called on Auth.SignoutHandler. InvalidateToken(ctx stdContext.Context, standardClaims StandardClaims, t T) error // InvalidateTokens is like InvalidateToken but it should invalidate // all tokens generated for a specific T value. // It can be an empty method too which returns a nil error. // // The first input argument standard context can be // casted to iris.Context if executed through Auth.SignoutAllHandler. // // It's called on Auth.SignoutAllHandler. InvalidateTokens(ctx stdContext.Context, t T) error }
Provider is an interface of T which MUST be completed by a custom value type to provide user information to the Auth's JWT Token Signer and Verifier.
A provider can optionally complete the Transformer, ClaimsProvider and ErrorHandler all in once when necessary. Set a provider using the AddProvider method of Auth type.
Example can be found at: https://github.com/kataras/iris/tree/master/_examples/auth/auth/user_provider.go.
type RefreshRequest ¶
type RefreshRequest struct {
RefreshToken string `json:"refresh_token"`
}
RefreshRequest is the request body the server expects on VerifyHandler to renew an access and refresh token pair.
type SigninRequest ¶
type SigninRequest struct { Username string `json:"username" form:"username,omitempty"` // username OR email, username has priority over email. Email string `json:"email" form:"email,omitempty"` // email OR username. Password string `json:"password" form:"password"` }
SigninRequest is the request body the server expects on SignHandler. The Password and Username or Email should be filled.
type SigninResponse ¶
type SigninResponse struct { AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token,omitempty"` }
SigninResponse is the response body the server sends to the client on the SignHandler. It contains a pair of the access token and the refresh token if the refresh jwt token id exists in the configuration.
type StandardClaims ¶
StandardClaims is an alias of jwt.Claims, it holds the standard JWT claims.
func GetStandardClaims ¶
func GetStandardClaims(ctx *context.Context) StandardClaims
GetStandardClaims accepts the iris Context and returns the standard token's claims. It's only available after Auth.VerifyHandler is executed.
type Transformer ¶
type Transformer[T User] interface { Transform(ctx stdContext.Context, tok *VerifiedToken) (T, error) }
Transformer is an optional interface which can be implemented by a Provider as well. Set a Transformer through Auth.SetTransformer or Auth.SetTransformerFunc or by implementing the Transform method inside a Provider which can be registered through the Auth.AddProvider method.
A transformer is called on Auth.VerifyHandler before Provider.ValidateToken and it can be used to modify the T value based on the token's contents. It is mostly used to convert the json claims to T value manually, when they differ.
The first input argument standard context can be casted to iris.Context if executed through Auth.VerifyHandler.
type TransformerFunc ¶
type TransformerFunc[T User] func(ctx stdContext.Context, tok *VerifiedToken) (T, error)
TransformerFunc completes the Transformer interface.
func (TransformerFunc[T]) Transform ¶
func (fn TransformerFunc[T]) Transform(ctx stdContext.Context, tok *VerifiedToken) (T, error)
Transform calls itself.
type User ¶
type User = any
User is an alias of an empty interface, it's here to declare the typeof T, which can be any custom struct type.
Example can be found at: https://github.com/kataras/iris/tree/master/_examples/auth/auth/user.go.
type VerifiedToken ¶
type VerifiedToken = jwt.VerifiedToken
VerifiedToken holds the information about a verified token.
type VerifyUserFunc ¶
VerifyUserFunc is passed on Verify and VerifyHandler method to, optionally, further validate a T user value.