jwt

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 16, 2024 License: MIT Imports: 8 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithAllowTokenHeader

func WithAllowTokenHeader[T any](header string) kit.Option[Management[T]]

WithAllowTokenHeader sets the name of the HTTP header from which the access token will be retrieved.

Parameters: - header: The name of the HTTP header.

Returns: - kit.Option[Management[T]]: A functional option to set the allowTokenHeader field in the Management structure.

func WithDecryptKey

func WithDecryptKey(decryptKey string) kit.Option[Options]

WithDecryptKey is a functional option that sets the decryption key in Options.

Parameters: - decryptKey: The key to be used for decryption.

Returns: - kit.Option[Options]: A functional option to set the decryptKey field in Options.

func WithExposeAccessHeader

func WithExposeAccessHeader[T any](header string) kit.Option[Management[T]]

WithExposeAccessHeader sets the name of the HTTP header that will expose the access token in the response.

Parameters: - header: The name of the HTTP header.

Returns: - kit.Option[Management[T]]: A functional option to set the exposeAccessHeader field in the Management structure.

func WithExposeRefreshHeader

func WithExposeRefreshHeader[T any](header string) kit.Option[Management[T]]

WithExposeRefreshHeader sets the name of the HTTP header that will expose the refresh token in the response.

Parameters: - header: The name of the HTTP header.

Returns: - kit.Option[Management[T]]: A functional option to set the exposeRefreshHeader field in the Management structure.

func WithGenIDFunc

func WithGenIDFunc(fn func() string) kit.Option[Options]

WithGenIDFunc is a functional option that sets the ID generation function in Options.

Parameters: - fn: A function that generates a unique string ID.

Returns: - kit.Option[Options]: A functional option to set the genIDFn field in Options.

func WithIssuer

func WithIssuer(issuer string) kit.Option[Options]

WithIssuer is a functional option that sets the issuer in Options.

Parameters: - issuer: The party who issues the JWT.

Returns: - kit.Option[Options]: A functional option to set the Issuer field in Options.

func WithMethod

func WithMethod(method jwt.SigningMethod) kit.Option[Options]

WithMethod is a functional option that sets the signing method in Options.

Parameters: - method: JWT signing method.

Returns: - kit.Option[Options]: A functional option to set the Method field in Options.

func WithNowFunc

func WithNowFunc[T any](nowFunc func() time.Time) kit.Option[Management[T]]

WithNowFunc customizes the function used to obtain the current time, useful for time-related operations like token expiry.

Parameters: - nowFunc: A function that returns the current time.

Returns: - kit.Option[Management[T]]: A functional option to set the nowFunc field in the Management structure.

func WithRefreshJWTOptions

func WithRefreshJWTOptions[T any](refreshOpts Options) kit.Option[Management[T]]

WithRefreshJWTOptions sets the configurations for creating refresh JWTs.

Parameters: - refreshOpts: A set of options used to configure refresh JWTs.

Returns: - kit.Option[Management[T]]: A functional option to assign the refreshJWTOptions field in the Management structure.

func WithRotateRefreshToken

func WithRotateRefreshToken[T any](isRotate bool) kit.Option[Management[T]]

WithRotateRefreshToken determines whether a new refresh token should be generated when refreshing an access token.

Parameters: - isRotate: A boolean flag indicating if refresh token rotation should occur.

Returns: - kit.Option[Management[T]]: A functional option to set the rotateRefreshToken field in the Management structure.

Types

type Management

type Management[T any] struct {
	// contains filtered or unexported fields
}

Management holds configurations for JWT authentication and refresh tokens, with support for generic data types.

Fields: - allowTokenHeader: Name of the HTTP header to check for the access token. - exposeAccessHeader: Name of the HTTP header used to expose the access token in the response. - exposeRefreshHeader: Name of the HTTP header used to expose the refresh token in the response. - accessJWTOptions: Configuration for the JWT access tokens. - refreshJWTOptions: Optional configuration for the JWT refresh tokens (may be nil if not used). - rotateRefreshToken: Flag indicating whether to issue a new refresh token when refreshing an access token. - nowFunc: Function that returns the current time, used for setting token issuance and expiration timestamps.

Type Parameter: - T: Represents the general type of the data included in the JWT claims.

func InitManagement

func InitManagement[T any](accessJWTOptions Options, opts ...kit.Option[Management[T]]) *Management[T]

InitManagement initializes a Management structure with specified JWT options and additional optional configurations.

Parameters: - accessJWTOptions: A set of options used to create access JWTs. - opts: A variadic parameter that can include additional options to customize the Management structure.

Returns: - *Management[T]: A pointer to the newly initialized Management structure parameterized by T.

func (*Management[T]) GenerateAccessToken

func (m *Management[T]) GenerateAccessToken(data T) (string, error)

GenerateAccessToken creates a new JSON Web Token (JWT) as an access token for the provided data.

Parameters: - data: The payload or claims to be embedded within the access token.

Returns: - string: The newly generated JWT access token. - Error: Error returned in case of failure in token generation.

func (*Management[T]) GenerateRefreshToken

func (m *Management[T]) GenerateRefreshToken(data T) (string, error)

GenerateRefreshToken creates a new refresh token for the supplied data.

Parameters: - data: The payload or specific data for which the refresh token is to be generated.

Returns: - string: The newly created refresh token. - Error: Error returned in case of failure in refresh token generation.

func (*Management[T]) MiddlewareBuilder

func (m *Management[T]) MiddlewareBuilder() *MiddlewareBuilder[T]

MiddlewareBuilder builds and returns a new instance of MiddlewareBuilder, which is used to create middleware based on the Management[T] configuration.

Returns: - *MiddlewareBuilder[T]: An instance of MiddlewareBuilder that can be used to create middleware.

func (*Management[T]) Refresh

func (m *Management[T]) Refresh(ctx *mist.Context)

Refresh handles the token refresh mechanism within the given request context. If the refresh token configurations are not set, an internal server error response is returned.

Parameters: - ctx: The request context that contains the HTTP request and response details.

func (*Management[T]) SetClaims

func (m *Management[T]) SetClaims(ctx *mist.Context, claims RegisteredClaims[T])

SetClaims is a helper function that stores the claims in the context of the request.

Parameters: - ctx: The context of the request where the claims should be stored. - claims: The claims to be stored in the request context for further processing in the security flow.

func (*Management[T]) VerifyAccessToken

func (m *Management[T]) VerifyAccessToken(token string, opts ...jwt.ParserOption) (RegisteredClaims[T], error)

VerifyAccessToken verifies the given access token string and returns the associated claims if the token is valid.

Parameters: - token: The JWT token to be verified. - opts: Parser options to provide additional conditions for token validation.

Returns: - RegisteredClaims[T]: The claims extracted from the validated token. - error: Error returned if the token is invalid or the verification process fails.

func (*Management[T]) VerifyRefreshToken

func (m *Management[T]) VerifyRefreshToken(token string, opts ...jwt.ParserOption) (RegisteredClaims[T], error)

VerifyRefreshToken checks the validity of the given refresh token and extracts its claims.

Parameters: - token: The refresh token to be validated. - opts: Additional parser options for the verification process.

Returns: - RegisteredClaims[T]: The registered claims present in the refresh token. - error: Error returned if verification fails or the refresh token is invalid.

type Manager

type Manager[T any] interface {
	// MiddlewareBuilder is a method that returns a pointer to an instance of MiddlewareBuilder.
	// This builder can be used to set up proper middleware for request handling.
	MiddlewareBuilder() *MiddlewareBuilder[T]

	// Refresh is a method to refresh the context of the middleware.
	// It could be used for updating/refreshing authentication or any other context-specific data.
	Refresh(ctx *mist.Context)

	// GenerateAccessToken is a method to generate a new access token from provided data.
	// The data type is dynamic and can be adjusted as needed. The function returns the generated token as a string and any possible error.
	GenerateAccessToken(data T) (string, error)

	// VerifyAccessToken verifies the provided JWT token and returns the associated claims or an error.
	// The 'opts' argument provides additional options to the jwt.Parser and is optional.
	VerifyAccessToken(token string, opts ...jwt.ParserOption) (RegisteredClaims[T], error)

	// GenerateRefreshToken is used to generate a new refresh token from the provided data.
	GenerateRefreshToken(data T) (string, error)

	// VerifyRefreshToken verifies the provided refresh token string and returns the associated claims or error.
	VerifyRefreshToken(token string, opts ...jwt.ParserOption) (RegisteredClaims[T], error)

	// SetClaims is a method to set registered claims to the current context.
	// The 'claims' parameter represents the registered claims to be set.
	SetClaims(ctx *mist.Context, claims RegisteredClaims[T])
}

Manager is an interface for managing middleware, tokens, and claims. It is generic to allow different data types.

type MiddlewareBuilder

type MiddlewareBuilder[T any] struct {
	// contains filtered or unexported fields
}

MiddlewareBuilder provides templates for constructing middleware relevant to authentication.

Fields: - ignorePath: A function used to determine if the provided path should be ignored by the middleware. - manager: A pointer to Management the provides tools to manage JWT tokens and their lifecycle. - nowFunc: A function that returns the current time, used for token expiry checks.

Generics: - T: A type parameter that allows the builder to be used with various data types.

func (*MiddlewareBuilder[T]) Build

func (m *MiddlewareBuilder[T]) Build() mist.Middleware

Build constructs the middleware function that can be integrated into an HTTP handling pipeline.

Returns: - mist.Middleware: The middleware with embedded logic for token validation and path ignoring.

func (*MiddlewareBuilder[T]) IgnorePath

func (m *MiddlewareBuilder[T]) IgnorePath(path ...string) *MiddlewareBuilder[T]

IgnorePath sets the paths that should be ignored by the middleware and returns the MiddlewareBuilder. Any requests matching the ignored paths will skip token validation.

Parameters: - path: A list of strings that represent the paths to ignore.

Returns: - *MiddlewareBuilder[T]: A pointer to the MiddlewareBuilder for method chaining.

func (*MiddlewareBuilder[T]) IgnorePathFunc

func (m *MiddlewareBuilder[T]) IgnorePathFunc(fn func(path string) bool) *MiddlewareBuilder[T]

IgnorePathFunc sets a custom function to determine if middleware should ignore a path.

Parameters: - fn: A function that takes a path string as input and returns a bool indicating if the path should be ignored.

Returns: - *MiddlewareBuilder[T]: A pointer to the MiddlewareBuilder for method chaining.

type Options

type Options struct {
	Expire        time.Duration     // Duration before a token expires.
	EncryptionKey string            // Key used for JWT encryption.
	DecryptKey    string            // Key used for JWT decryption, defaults to EncryptionKey if not provided.
	Method        jwt.SigningMethod // Method used to sign the JWT.
	Issuer        string            // Name or identifier of the issuer of the JWT.
	// contains filtered or unexported fields
}

Options define the configuration for JWT token management.

Parameters: - Expire: A time.Duration value indicating the expiration duration of the token. - EncryptionKey: A string value used for token encryption.

Returns: - Options: This method returns an Options struct initialized with the provided parameters or defaults.

func InitOptions

func InitOptions(expire time.Duration, encryptionKey string,
	opts ...kit.Option[Options]) Options

InitOptions initializes and returns an Options struct with given parameters and additional options.

Parameters: - expire: Duration before the token expires. - encryptionKey: Key used for token encryption. - opts: Optional functional parameters to customize the Options further.

Returns: - Options: A struct containing configuration options for JWT token management.

type RegisteredClaims

type RegisteredClaims[T any] struct {
	// The Data portion of the claim can be of any type 'T' and it is denoted in JSON representation as "data".
	Data T `json:"data"`
	// RegisteredClaims from JWT are embedded to contain standard claims defined in JWT specifications.
	jwt.RegisteredClaims
}

RegisteredClaims is a struct to hold data and registered JWT claims. The 'T' makes it robust to hold various types of data.

Jump to

Keyboard shortcuts

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