auth

package
v5.0.0-preview5 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2023 License: MIT Imports: 22 Imported by: 4

Documentation

Index

Constants

View Source
const (
	// JWTServiceName identifier for the `JWTService`.
	JWTServiceName = "goyave.jwt"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Authenticator

type Authenticator interface {
	goyave.Composable

	// Authenticate fetch the user corresponding to the credentials
	// found in the given request and puts the result in the given user pointer.
	// If no user can be authenticated, returns the error detailing why the
	// authentication failed. The error message is already localized.
	//
	// The `user` is a double pointer to a `nil` structure defined by the generic
	// parameter of the middleware.
	Authenticate(request *goyave.Request, user any) error
}

Authenticator is an object in charge of authenticating a model.

type BasicAuthenticator

type BasicAuthenticator struct {
	goyave.Component

	// Optional defines if the authenticator allows requests that
	// don't provide credentials. Handlers should therefore check
	// if request.User is not nil before accessing it.
	Optional bool
}

BasicAuthenticator implementation of Authenticator with the Basic authentication method.

func (*BasicAuthenticator) Authenticate

func (a *BasicAuthenticator) Authenticate(request *goyave.Request, user any) error

Authenticate fetch the user corresponding to the credentials found in the given request and puts the result in the given user pointer. If no user can be authenticated, returns an error.

The database request is executed based on the model name and the struct tags `auth:"username"` and `auth:"password"`. The password is checked using bcrypt. The username field should unique.

type BasicUser

type BasicUser struct {
	Name string
}

BasicUser a simple user for config-based basic authentication.

type Column

type Column struct {
	Field *reflect.StructField
	Name  string
}

Column matches a column name with a struct field.

func FindColumns

func FindColumns(db *gorm.DB, strct any, fields ...string) []*Column

FindColumns in given struct. A field matches if it has a "auth" tag with the given value. Returns a slice of found fields, ordered as the input "fields" slice. If the nth field is not found, the nth value of the returned slice will be nil.

Promoted fields are matched as well.

Given the following struct and "username", "notatag", "password":

 type TestUser struct {
		gorm.Model
		Name     string `gorm:"type:varchar(100)"`
		Password string `gorm:"type:varchar(100)" auth:"password"`
		Email    string `gorm:"type:varchar(100);uniqueIndex" auth:"username"`
 }

The result will be the "Email" field, "nil" and the "Password" field.

type ConfigBasicAuthenticator

type ConfigBasicAuthenticator struct {
	goyave.Component
}

ConfigBasicAuthenticator implementation of Authenticator with the Basic authentication method, using username and password from the configuration.

func (*ConfigBasicAuthenticator) Authenticate

func (a *ConfigBasicAuthenticator) Authenticate(request *goyave.Request, user any) error

Authenticate check if the request basic auth header matches the "auth.basic.username" and "auth.basic.password" config entries.

type Handler

type Handler[T any] struct {
	Authenticator
}

Handler a middleware that automatically sets the request's User before executing the authenticator. Supports the `Unauthorizer` interface.

The T parameter represents the user model and should be a pointer.

func ConfigBasicAuth

func ConfigBasicAuth() *Handler[*BasicUser]

ConfigBasicAuth create a new authenticator middleware for config-based Basic authentication. On auth success, the request user is set to a `*BasicUser`. The user is authenticated if the "auth.basic.username" and "auth.basic.password" config entries match the request's Authorization header.

func Middleware

func Middleware[T any](authenticator Authenticator) *Handler[T]

Middleware returns an authentication middleware which will use the given authenticator and set the request's user according to the given model.

func (*Handler[T]) Handle

func (m *Handler[T]) Handle(next goyave.Handler) goyave.Handler

Handle set the request's user to a new instance of the model before executing the authenticator. Blocks if the authentication is not successful. If the authenticator implements `Unauthorizer`, `OnUnauthorized` is called, otherwise returns a default `401 Unauthorized` error.

type JWTAuthenticator

type JWTAuthenticator struct {
	goyave.Component

	// SigningMethod expected by this authenticator when parsing JWT.
	// Defaults to HMAC.
	SigningMethod jwt.SigningMethod

	// ClaimName the name of the claim used to retrieve the user.
	// Defaults to "sub".
	ClaimName string

	// Optional defines if the authenticator allows requests that
	// don't provide credentials. Handlers should therefore check
	// if request.User is not nil before accessing it.
	Optional bool
	// contains filtered or unexported fields
}

JWTAuthenticator implementation of Authenticator using a JSON Web Token.

func (*JWTAuthenticator) Authenticate

func (a *JWTAuthenticator) Authenticate(request *goyave.Request, user any) error

Authenticate fetch the user corresponding to the token found in the given request and puts the result in the given user pointer. If no user can be authenticated, returns an error.

The database request is executed based on the model name and the struct tag `auth:"username"`.

If the token is valid and has claims, those claims will be added to `request.Extra` with the key "jwt_claims".

This implementation is a JWT-based authentication using HMAC SHA256, supporting only one active token.

func (*JWTAuthenticator) Init

func (a *JWTAuthenticator) Init(server *goyave.Server)

Init the authenticator. Automatically registers the `JWTService` if not already registered, using `osfs.FS` as file system for the keys.

type JWTController

type JWTController[T any] struct {
	goyave.Component

	// SigningMethod used to generate the token using the default
	// TokenFunc. By default, uses `jwt.SigningMethodHS256`.
	SigningMethod jwt.SigningMethod

	// The function generating the token on a successful authentication.
	// Defaults to a JWT signed with HS256 and containing the username as the
	// "sub" claim.
	TokenFunc TokenFunc[T]

	// UsernameField the name of the request's body field
	// used as username in the authentication process.
	// Defaults to "username"
	UsernameField string
	// PasswordField the name of the request's body field
	// used as password in the authentication process.
	// Defaults to "password"
	PasswordField string
	// contains filtered or unexported fields
}

JWTController controller adding a login route returning a JWT for quick prototyping.

The T parameter represents the user model and should NOT be a pointer.

func (*JWTController[T]) Init

func (c *JWTController[T]) Init(server *goyave.Server)

Init the controller. Automatically registers the `JWTService` if not already registered, using `osfs.FS` as file system for the signing keys.

func (*JWTController[T]) Login

func (c *JWTController[T]) Login(response *goyave.Response, request *goyave.Request)

Login POST handler for token-based authentication. Creates a new token for the user authenticated with the body fields defined in the controller and returns it as a response. (the "username" and "password" body field are used by default)

The database request is executed based on the model name and the struct tags `auth:"username"` and `auth:"password"`. The password is checked using bcrypt. The username field should unique.

func (*JWTController[T]) RegisterRoutes

func (c *JWTController[T]) RegisterRoutes(router *goyave.Router)

RegisterRoutes register the "/login" route (with validation) on the given router.

type JWTService

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

JWTService providing signature keys cache and JWT generation.

This service is identified by `auth.JWTServiceName`.

func NewJWTService

func NewJWTService(config *config.Config, fs fs.FS) *JWTService

NewJWTService create a new `JWTService` with the given config and file system. The file system is used to get the signing keys.

func (*JWTService) GenerateToken

func (s *JWTService) GenerateToken(username any) (string, error)

GenerateToken generate a new JWT. The token is created using the HMAC SHA256 method and signed using the `auth.jwt.secret` config entry. The token is set to expire in the amount of seconds defined by the `auth.jwt.expiry` config entry.

The generated token will contain the following claims:

  • `sub`: has the value of the `id` parameter
  • `nbf`: "Not before", the current timestamp is used
  • `exp`: "Expiry", the current timestamp plus the `auth.jwt.expiry` config entry.

func (*JWTService) GenerateTokenWithClaims

func (s *JWTService) GenerateTokenWithClaims(claims jwt.MapClaims, signingMethod jwt.SigningMethod) (string, error)

GenerateTokenWithClaims generates a new JWT with custom claims. The token is set to expire in the amount of seconds defined by the `auth.jwt.expiry` config entry. Depending on the given signing method, the following configuration entries will be used:

  • RSA: `auth.jwt.rsa.private`: path to the private PEM-encoded RSA key.
  • ECDSA: `auth.jwt.ecdsa.private`: path to the private PEM-encoded ECDSA key.
  • HMAC: `auth.jwt.secret`: HMAC secret

The generated token will also contain the following claims:

  • `nbf`: "Not before", the current timestamp is used
  • `exp`: "Expiry", the current timestamp plus the `auth.jwt.expiry` config entry.

`nbf` and `exp` can be overridden if they are set in the `claims` parameter.

func (*JWTService) GetKey

func (s *JWTService) GetKey(entry string) (any, error)

GetKey load a JWT signature key from the config. List of `entry` parameter possible values:

  • `auth.jwt.rsa.public`
  • `auth.jwt.rsa.private`
  • `auth.jwt.ecdsa.public`
  • `auth.jwt.ecdsa.private`
  • `auth.jwt.secret`

To optimize subsequent requests and avoid IO for keys that are stored on the disk, the keys are cached.

func (*JWTService) GetPrivateKey

func (s *JWTService) GetPrivateKey(signingMethod jwt.SigningMethod) (any, error)

GetPrivateKey loads the private key that corresponds to the given `signingMethod`.

func (*JWTService) Name

func (s *JWTService) Name() string

Name returns the name of the service.

type TokenFunc

type TokenFunc[T any] func(request *goyave.Request, user *T) (string, error)

TokenFunc is the function used by JWTController to generate tokens during login process.

type Unauthorizer

type Unauthorizer interface {
	OnUnauthorized(*goyave.Response, *goyave.Request, error)
}

Unauthorizer can be implemented by Authenticators to define custom behavior when authentication fails.

Jump to

Keyboard shortcuts

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