auth

package
v1.9.1 Latest Latest
Warning

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

Go to latest
Published: Mar 18, 2026 License: MIT Imports: 11 Imported by: 0

README

rex.auth

Package auth provides session-based authentication middleware for the Rex router. It uses secure cookie sessions to maintain authentication state and supports storing custom user state in the session.

Installation

go get -u github.com/abiiranathan/rex

Basic usage:

authMiddleware, err := auth.NewCookieAuth(
    "session",
    [][]byte{[]byte("your-32-byte-auth-key")},
    User{},
    auth.CookieConfig{
        ErrorHandler: func(c *rex.Context) error {
            return c.Status(http.StatusUnauthorized).JSON(map[string]string{
                "error": "Unauthorized",
            })
        },
    },
)
if err != nil {
    log.Fatalf("unable to initialize cookie auth: %v", err)
}

// Use the middleware in your router
router := rex.NewRouter()
router.Use(authMiddleware.Middleware())

Login example:

router.Post("/login", func(c *rex.Context) error {
    user := &User{ID: 1, Name: "John"}
    if err := authMiddleware.SetState(c, user); err != nil {
        return err
    }
    return c.JSON(user)
})

Access authenticated user:

router.Get("/me", func(c *rex.Context) error {
    state := authMiddleware.Value(c)
    if state == nil {
        return c.Status(http.StatusUnauthorized)
    }
    user := state.(*User)
    return c.JSON(user)
})

Logout example:

router.Post("/logout", func(c *rex.Context) error {
    if err := authMiddleware.Clear(c); err != nil {
        return err
    }
    return c.Status(http.StatusNoContent)
})

Security Notes:

  • Cookie sessions are encrypted and authenticated using the provided key pairs
  • HttpOnly and SameSite=Strict are enforced for security
  • Default session duration is 24 hours
  • Use cryptographically secure random bytes for key pairs
  • For production, use https://pkg.go.dev/crypto/rand to generate keys

Key Generation Example:

	key := make([]byte, 32)
	if _, err := rand.Read(key); err != nil {
		panic(err)
	}

For key rotation, you can provide multiple key pairs:

authMiddleware, err := auth.NewCookieAuth("session", [][]byte{
    []byte("new-32-byte-auth-key"),
    []byte("new-32-byte-encrypt-key"),
    []byte("old-32-byte-auth-key"),
    []byte("old-32-byte-encrypt-key"),
}, User{}, auth.CookieConfig{/* ... */})
if err != nil {
    log.Fatalf("unable to initialize cookie auth: %v", err)
}

Custom cookie options:

authMiddleware, err := auth.NewCookieAuth("session", [][]byte{[]byte("your-32-byte-auth-key")}, User{}, auth.CookieConfig{
    Options: &sessions.Options{
        Path:   "/",
        Domain: "example.com",
        MaxAge: 3600,
        Secure: true,
    },
})
if err != nil {
    log.Fatalf("unable to initialize cookie auth: %v", err)
}

Skip authentication for specific routes:

authMiddleware, err := auth.NewCookieAuth("session", [][]byte{[]byte("your-32-or-64-byte-auth-key")}, User{}, auth.CookieConfig{
    SkipAuth: func(c *rex.Context) bool {
        return c.Path() == "/login" || c.Path() == "/signup"
    },
})
if err != nil {
    log.Fatalf("unable to initialize cookie auth: %v", err)
}

It also provides middleware for BasicAuth, JWT auth.
Oauth2 support is coming soon.

Documentation

Overview

Package auth provides session-based authentication middleware for the Rex router. It uses secure cookie sessions to maintain authentication state and supports storing custom user state in the session. It also provide JWT and BasicAuth middleware. View the README for more information.

Index

Constants

This section is empty.

Variables

View Source
var ErrNotInitialized = errors.New("auth: cookie auth is not initialized")

ErrNotInitialized is returned when a CookieAuth instance is nil or missing its store.

Functions

func BasicAuth

func BasicAuth(username, password string, realm ...string) rex.Middleware

BasicAuth returns middleware that protects routes with HTTP Basic authentication. If the credentials are invalid, it responds with status 401. The default realm is "Restricted".

func CreateJWTToken

func CreateJWTToken(secret string, payload any, exp time.Duration) (string, error)

CreateJWTToken creates a JWT token with the given payload and expiry duration. The token is signed with the secret key using HMAC SHA-256.

func DefaultErrorHandler added in v1.9.0

func DefaultErrorHandler(c *rex.Context) error

DefaultErrorHandler returns HTTP 401 for unauthenticated requests.

func JWT

func JWT(secret string, skipFunc func(c *rex.Context) bool) rex.Middleware

JWT creates a JWT middleware with the given secret and options. If skipFunc returns true, authentication is skipped.

func JWTAuthSkipped added in v1.0.3

func JWTAuthSkipped(r *http.Request) bool

JWTAuthSkipped reports whether JWT authentication was skipped for the request.

func JwtClaims added in v1.0.5

func JwtClaims(req *http.Request) (jwt.MapClaims, error)

JwtClaims returns the JWT claims stored on the request context. It should be called after JWT verification has completed.

func VerifyJWToken

func VerifyJWToken(secret, tokenString string) (jwt.MapClaims, error)

VerifyJWToken verifies the given JWT token with the secret key. Returns the claims if the token is valid, otherwise an error. The token is verified using the HMAC256 algorithm. The default claims are stored in the "payload" key and the expiry time in the "exp" key.

Types

type CookieAuth added in v1.9.0

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

CookieAuth encapsulates session cookie authentication state and behavior.

func NewCookieAuth added in v1.9.0

func NewCookieAuth(sessionName string, keyPairs [][]byte, userType any, config CookieConfig) (*CookieAuth, error)

NewCookieAuth creates a cookie authentication instance with its own store and session name.

func (*CookieAuth) Clear added in v1.9.0

func (a *CookieAuth) Clear(c *rex.Context)

Clear deletes authentication state for this instance.

func (*CookieAuth) Middleware added in v1.9.0

func (a *CookieAuth) Middleware() rex.Middleware

Middleware returns the cookie authentication middleware for this instance.

func (*CookieAuth) SetState added in v1.9.0

func (a *CookieAuth) SetState(c *rex.Context, state any) error

SetState stores authentication state for this instance.

func (*CookieAuth) Skipped added in v1.9.0

func (a *CookieAuth) Skipped(c *rex.Context) bool

Skipped reports whether this request skipped cookie authentication.

func (*CookieAuth) Value added in v1.9.0

func (a *CookieAuth) Value(c *rex.Context) any

Value returns the auth state for this request or nil if not logged in.

type CookieConfig

type CookieConfig struct {
	// Cookie options.
	// Default: HttpOnly=true, SameSite=Strict(always), MaxAge=24hrs, Domain=/,secure=false
	Options *sessions.Options

	// Skip authentication for certain requests
	SkipAuth func(c *rex.Context) bool

	// Called when authentication fails
	ErrorHandler func(c *rex.Context) error
}

CookieConfig defines the behavior of the cookie authentication middleware.

type CtxKey added in v1.9.0

type CtxKey string

CtxKey identifies auth-related values stored in the request context.

Jump to

Keyboard shortcuts

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