ginjwt

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2024 License: Apache-2.0 Imports: 15 Imported by: 1

Documentation

Overview

Package ginjwt provides a JWT authentication and authorization middleware for use with a gin server

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidAudience is the error returned when the audience of the token isn't what we expect
	ErrInvalidAudience = errors.New("invalid JWT audience")

	// ErrInvalidIssuer is the error returned when the issuer of the token isn't what we expect
	ErrInvalidIssuer = errors.New("invalid JWT issuer")

	// ErrInvalidAuthConfig is an error returned when the oidc auth config isn't able to be unmarshaled
	ErrInvalidAuthConfig = errors.New("invalid oidc config provided")

	// ErrMissingAuthConfig is an error returned when the oidc auth config isn't provided via a command line flag.
	ErrMissingAuthConfig = errors.New("oidc auth config wasn't provided")

	// ErrMissingIssuerFlag is an error returned when the issuer isn't provided via a command line flag.
	ErrMissingIssuerFlag = errors.New("issuer wasn't provided")

	// ErrMissingJWKURIFlag is an error returned when the JWK URI isn't provided via a command line flag.
	ErrMissingJWKURIFlag = errors.New("JWK URI wasn't provided")

	// ErrJWKSConfigConflict is an error when both JWKSURI and JWKS are set
	ErrJWKSConfigConflict = errors.New("JWKS and JWKSURI can't both be set at the same time")
)

Functions

func BindFlagFromViperInst

func BindFlagFromViperInst(v *viper.Viper, name string, flag *pflag.Flag)

BindFlagFromViperInst provides a wrapper around the viper bindings that handles error checks

func CreateScopes

func CreateScopes(items ...string) []string

CreateScopes will return a list of scopes allowed for creating the items that are passed in

func DeleteScopes

func DeleteScopes(items ...string) []string

DeleteScopes will return a list of scopes allowed for deleting the items that are passed in.

func GetSubject

func GetSubject(c *gin.Context) string

GetSubject will return the JWT subject that is saved in the request. This requires that authentication of the request has already occurred. If authentication failed or there isn't a user, an empty string is returned. This returns whatever value was in the JWT subject field and might not be a human readable value

func GetUser

func GetUser(c *gin.Context) string

GetUser will return the JWT user that is saved in the request. This requires that authentication of the request has already occurred. If authentication failed or there isn't a user an empty string is returned.

func NewMultiTokenMiddlewareFromConfigs

func NewMultiTokenMiddlewareFromConfigs(cfgs ...AuthConfig) (*ginauth.MultiTokenMiddleware, error)

NewMultiTokenMiddlewareFromConfigs builds a MultiTokenMiddleware object from multiple AuthConfigs.

func ReadScopes

func ReadScopes(items ...string) []string

ReadScopes will return a list of scopes allowed for creating the items that are passed in.

func RegisterViperOIDCFlags

func RegisterViperOIDCFlags(v *viper.Viper, cmd *cobra.Command)

RegisterViperOIDCFlags ensures that the given Viper and cobra.Command instances have the following command line/configuration flags registered:

- oidc: Enables/disables OIDC authentication.

- oidc-aud: Specifies the expected audience for the JWT token.

- oidc-issuer: Specifies the expected issuer for the JWT token (can be more than one value).

- oidc-jwksuri: Specifies the JSON Web Key Set (JWKS) URI (can be more than one value).

- oidc-roles-claim: Specifies the roles to be accepted for the JWT claim.

- oidc-username-claim: Specifies a username to use for the JWT claim.

- oidc-jwks-remotetimeout: Specifies a timeout for the JWKS URI.

A call to this would normally look as follows:

ginjwt.RegisterViperOIDCFlags(viper.GetViper(), serveCmd)

The oidc configuration should be passed in through a yaml file due to the nested structure of the fields, however, if only one oidc provider is used the flag parameters would work.

func UpdateScopes

func UpdateScopes(items ...string) []string

UpdateScopes will return a list of scopes allowed for updating the items that are passed in.

func ViperBindFlag

func ViperBindFlag(name string, flag *pflag.Flag)

ViperBindFlag provides a wrapper around the viper bindings that handles error checks

Types

type AuthConfig

type AuthConfig struct {
	Enabled  bool
	Audience string
	Issuer   string
	JWKSURI  string

	// JWKS allows the user to specify the JWKS directly instead of through URI
	JWKS              jose.JSONWebKeySet
	LogFields         []string
	RolesClaim        string
	UsernameClaim     string
	JWKSRemoteTimeout time.Duration
	// Role validation strategy for roles claim. Defaults to any if unspecified.
	RoleValidationStrategy RoleValidationStrategy
}

AuthConfig provides the configuration for the authentication service

func GetAuthConfigFromFlags

func GetAuthConfigFromFlags(v *viper.Viper) (AuthConfig, error)

GetAuthConfigFromFlags builds an AuthConfig object from flags provided by the viper tooling. This utility function assumes that the `RegisterViperOIDCFlags` function was called beforehand.

A call to this would normally look as follows:

ginjwt.GetAuthConfigFromFlags(viper.GetViper())

Note that when using this function configuration

func GetAuthConfigsFromFlags

func GetAuthConfigsFromFlags(v *viper.Viper) ([]AuthConfig, error)

GetAuthConfigsFromFlags builds AuthConfig objects from flags provided by the viper tooling. This utility function assumes that the `RegisterViperOIDCFlags` function was called beforehand.

A call to this would normally look as follows:

ginjwt.GetAuthConfigsFromFlags(viper.GetViper())

Note that this function will retrieve as many AuthConfigs as the number of issuers and JWK URIs given (which must match)

type Claims

type Claims struct {
	Roles    string `yaml:"roles"`
	Username string `yaml:"username"`
}

Claims defines the roles and username claims for the given oidc provider

type Middleware

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

Middleware provides a gin compatible middleware that will authenticate JWT requests

func NewAuthMiddleware

func NewAuthMiddleware(cfg AuthConfig) (*Middleware, error)

NewAuthMiddleware will return an auth middleware configured with the jwt parameters passed in

func (*Middleware) AuthRequired

func (m *Middleware) AuthRequired() gin.HandlerFunc

AuthRequired provides a middleware that ensures a request has authentication. In order to validate scopes, you also need to call RequireScopes().

func (*Middleware) RequiredScopes

func (m *Middleware) RequiredScopes(scopes []string) gin.HandlerFunc

RequiredScopes provides middleware that validates that the passed list of scopes are included in the role claims by checking the values on context.

func (*Middleware) SetMetadata

func (m *Middleware) SetMetadata(c *gin.Context, cm ginauth.ClaimMetadata)

SetMetadata sets the needed metadata to the gin context which came from the token

func (*Middleware) VerifyScopes

func (m *Middleware) VerifyScopes(c *gin.Context, scopes []string) error

VerifyScopes verifies role claims added to the gin.Context object. This implements the GenericMiddleware interface

func (*Middleware) VerifyToken

func (m *Middleware) VerifyToken(c *gin.Context) (ginauth.ClaimMetadata, error)

VerifyToken verifies a JWT token gotten from the gin.Context object. This does not validate roles claims/scopes. This implements the GenericMiddleware interface

func (*Middleware) VerifyTokenWithScopes

func (m *Middleware) VerifyTokenWithScopes(c *gin.Context, scopes []string) (ginauth.ClaimMetadata, error)

VerifyTokenWithScopes satisfies the goauth.GenericAuthMiddleware interface and exists only for backwards compatibility with that interface.

type OIDCConfig

type OIDCConfig struct {
	Enabled                bool                   `yaml:"enabled"`
	Audience               string                 `yaml:"audience"`
	Issuer                 string                 `yaml:"issuer"`
	JWKSURI                string                 `yaml:"jwsuri"`
	JWKSRemoteTimeout      time.Duration          `yaml:"jwksremotetimeout"`
	RoleValidationStrategy RoleValidationStrategy `yaml:"rolevalidationstrategy"`
	Claims                 Claims                 `yaml:"claims"`
}

OIDCConfig provides the configuration for the oidc provider auth configuration

type RoleValidationStrategy

type RoleValidationStrategy string

RoleValidationStrategy represents a validation strategy for roles.

const (
	// RoleValidationStrategyAny represents validation that any required role exists in the roles claim.
	RoleValidationStrategyAny RoleValidationStrategy = "any"
	// RoleValidationStrategyAll represents validation that all required roles exist in the roles claim.
	RoleValidationStrategyAll RoleValidationStrategy = "all"
)

Jump to

Keyboard shortcuts

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