jwt

package module
v0.0.0-...-242fd26 Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2023 License: AGPL-3.0 Imports: 10 Imported by: 0

README

solplay/jwt

JWT wrapper and middleware

Tests

Installation

go get github.com/solplaydev/jwt

License

This project is licensed under the The GNU Affero General Public License - see the LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	AuthTypeUser     = "u" // User auth (email/password)
	AuthTypeApp      = "a" // App auth (client id/secret)
	AuthTypeInternal = "i" // Internal auth, used for internal services. (client id/secret)
)

Predefined auth types for the claims

Variables

View Source
var (
	ClaimsKey = ContextKey{Key: "claims"}
	TokenKey  = ContextKey{Key: "token"}
)

Predefined context keys

View Source
var (
	ErrInvalidToken            = errors.New("invalid_token")
	ErrTokenMalformed          = errors.New("token_malformed")
	ErrTokenExpired            = errors.New("token_expired")
	ErrTokenNotActive          = errors.New("token_inactive")
	ErrFailedToParseClaims     = errors.New("failed_parse_claims")
	ErrUnexpectedSigningMethod = errors.New("unexpected_signing_method")
	ErrFailedToSignToken       = errors.New("failed_to_sign_token")
	ErrFailedToParseToken      = errors.New("failed_to_parse_token")
	ErrInvalidClaims           = errors.New("invalid_claims")
)

Predefined package errors.

Error codes.

View Source
var ErrorMessages = map[error]string{
	ErrInvalidToken:            "Invalid token",
	ErrTokenMalformed:          "Malformed token",
	ErrTokenExpired:            "Token expired",
	ErrTokenNotActive:          "Token not active yet",
	ErrFailedToParseClaims:     "Failed to parse claims",
	ErrUnexpectedSigningMethod: "Unexpected signing method",
	ErrFailedToSignToken:       "Failed to sign token",
	ErrFailedToParseToken:      "Failed to parse token",
	ErrInvalidClaims:           "Invalid claims type or missing required claims",
}

Error messages.

Functions

func GetClientIDFromContext

func GetClientIDFromContext(ctx context.Context) (string, error)

GetClientIDFromContext is a function that returns the client ID from the context

func GetScopeFromContext

func GetScopeFromContext(ctx context.Context) (string, error)

GetScopeFromContext is a function that returns the scope from the context

func GetSessionIDFromContext

func GetSessionIDFromContext(ctx context.Context) (string, error)

GetSessionIDFromContext is a function that returns the session ID from the context

func GetTokenFromContext

func GetTokenFromContext(ctx context.Context) (string, error)

GetTokenFromContext is a function that returns the token from the context

func GetTokenFromRequest

func GetTokenFromRequest(r *http.Request) (string, error)

GetTokenFromRequest is a function that returns the token string from the request (header or query parameter)

func GetUserIDFromContext

func GetUserIDFromContext(ctx context.Context) (string, error)

GetUserIDFromContext is a function that returns the user ID from the context

Types

type Claims

type Claims struct {
	// Standard claims
	jwt.StandardClaims
	// Custom claims
	UserID    string `json:"uid,omitempty"`
	ProjectID string `json:"pid,omitempty"`
	ClientID  string `json:"cid,omitempty"`
	Scope     string `json:"scope,omitempty"`
	AuthType  string `json:"auth,omitempty"`
}

Claims is a struct that contains the claims that are used in the JWT

func GetClaimsFromContext

func GetClaimsFromContext(ctx context.Context) (*Claims, error)

GetClaimsFromContext is a function that returns the claims from the context and casts them to the Claims type, if possible

func NewClaims

func NewClaims(opts ...ClaimsOption) Claims

NewClaims is a function that returns a new instance of the claims

func (Claims) CheckScopeInAllowed

func (c Claims) CheckScopeInAllowed(scope string) bool

CheckScopeInAllowed is a method that checks if the scope is in the allowed scopes

func (Claims) GetScopes

func (c Claims) GetScopes() []string

GetScopes is a method that returns the scopes as a slice

func (Claims) IsAppAuth

func (c Claims) IsAppAuth() bool

IsAppAuth is a method that returns true if the auth type is app

func (Claims) IsInternalAuth

func (c Claims) IsInternalAuth() bool

IsInternalAuth is a method that returns true if the auth type is internal

func (Claims) IsUserAuth

func (c Claims) IsUserAuth() bool

IsUserAuth is a method that returns true if the auth type is user

type ClaimsOption

type ClaimsOption func(*Claims)

ClaimsOption is a function that is used to set the claims options

func WithAudience

func WithAudience(audience string) ClaimsOption

WithAudience is a function that sets the audience in the claims

func WithAuthType

func WithAuthType(authType string) ClaimsOption

WithAuthType is a function that sets the auth type in the claims

func WithClientID

func WithClientID(clientID string) ClaimsOption

WithClientID is a function that sets the client id in the claims

func WithCustomAuthType

func WithCustomAuthType(authType string) ClaimsOption

WithCustomAuthType is a function that sets the auth type in the claims

func WithExpiresAt

func WithExpiresAt(expiresAt int64) ClaimsOption

WithExpiresAt is a function that sets the expires at in the claims Parameter expiresAt is the unix timestamp

func WithID

func WithID(id string) ClaimsOption

WithID is a function that sets the id in the claims

func WithIssuedAt

func WithIssuedAt(issuedAt int64) ClaimsOption

WithIssuedAt is a function that sets the issued at in the claims

func WithIssuer

func WithIssuer(issuer string) ClaimsOption

WithIssuer is a function that sets the issuer in the claims

func WithNotBefore

func WithNotBefore(notBefore int64) ClaimsOption

WithNotBefore is a function that sets the not before in the claims

func WithProjectID

func WithProjectID(projectID string) ClaimsOption

WithProjectID is a function that sets the project id in the claims

func WithScope

func WithScope(scope string) ClaimsOption

WithScope is a function that sets the scope in the claims

func WithSubject

func WithSubject(subject string) ClaimsOption

WithSubject is a function that sets the subject in the claims

func WithTTL

func WithTTL(ttl int64) ClaimsOption

WithTTL is a function that sets the expires at in the claims Parameter ttl is the time to live in seconds

func WithUserID

func WithUserID(userID string) ClaimsOption

WithUserID is a function that sets the user id in the claims

type ContextKey

type ContextKey struct{ Key string }

ContextKey is a struct that contains the key that is used to set the value in the context

func (ContextKey) String

func (c ContextKey) String() string

String is a method that returns the key as a string

type Error

type Error struct {
	Err  error  `json:"error,omitempty"`         // Original error.
	Code int    `json:"error_code,omitempty"`    // HTTP status code.
	Msg  string `json:"error_message,omitempty"` // Error message.
}

Error is a custom error type.

func NewError

func NewError(err error) *Error

NewError creates a new Error.

func (*Error) As

func (e *Error) As(err any) bool

As checks if the error can be converted to the given type.

func (*Error) Error

func (e *Error) Error() string

Error returns the error message.

func (*Error) Is

func (e *Error) Is(err error) bool

Is checks if the error is of the given type.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the original error.

type Interactor

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

Interactor is a struct that contains the methods that are used to interact with the JWT

func NewInteractor

func NewInteractor(signingKey []byte, ttl time.Duration) *Interactor

NewInteractor is a function that returns a new instance of the JWT interactor

func (*Interactor) GenerateToken

func (i *Interactor) GenerateToken(claims Claims) (string, error)

GenerateToken is a method that generates a new JWT token

func (*Interactor) ParseWithClaims

func (i *Interactor) ParseWithClaims(tokenStr string) (*Claims, error)

ParseWithClaims parses a JWT token and returns its claims.

type Middleware

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

func NewMiddleware

func NewMiddleware(jwtInteractor jwtInteractor, isRequired bool, skipper Skipper) *Middleware

NewMiddleware returns a new instance of the JWT middleware.

func (*Middleware) Default

func (m *Middleware) Default(scopes ...string) func(http.Handler) http.Handler

Default is a function that returns a new instance of the JWT middleware for net/http.

func (*Middleware) Echo

func (m *Middleware) Echo(scopes ...string) echo.MiddlewareFunc

Echo is a function that returns a new instance of the JWT middleware for Echo framework

type Skipper

type Skipper func(c context.Context) bool

Skipper defines a function to skip middleware.

Jump to

Keyboard shortcuts

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