auth

package
v14.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: BSD-3-Clause, BSD-3-Clause Imports: 22 Imported by: 0

README

Iris Authentication

The auth package signs users in and decides what they may do, using JSON Web Tokens. Your own struct is the user type, and your own function decides whether a set of credentials is valid.

Features

  • JWT-based authentication and authorization
  • Customizable user types
  • Support for access and refresh tokens
  • Single Sign-On (SSO)
  • Secure cookie handling
  • Custom error handling
  • Token invalidation
  • Extensible providers and AWS Cognito support, and more

Prerequisites

To use the auth package, you need to have a basic understanding of JWT and how it works. You can refer to the following resources for more information:

Installation

To use the auth package, you need to import it in your Iris application:

import "github.com/kataras/iris/v14/auth"

Configuration

Single Sign-On (SSO)

Single Sign-On (SSO) is an authentication process that allows a user to access multiple applications with one set of login credentials. This means that once a user logs in to one application, they can access other related applications without having to log in again. SSO improves user experience by reducing the number of times a user has to log in and enhances security by centralizing authentication.

SSO only holds up if the token cannot be read or altered in the browser, which is what the cookie configuration is for. Hash authenticates the cookie value with HMAC, so tampering is detected, and Block encrypts it, so the contents cannot be read. Set both.

The auth package requires a configuration file to set up the JWT keys and other settings. The configuration file can be in JSON or YAML format. Here is an example configuration file in YAML:

Headers:
  - "Authorization"
  - "X-Authorization"
Cookie:
  Name: "iris_auth_cookie"
  Secure: false
  Hash: "D*G-KaPdSgUkXp2s5v8y/B?E(H+MbQeThWmYq3t6w9z$C&F)J@NcRfUjXn2r4u7x"
  Block: "VkYp3s6v9y$B&E)H@McQfTjWmZq4t7w!"
Keys:
  - ID: IRIS_AUTH_ACCESS
    Alg: EdDSA
    MaxAge: 2h
    Private: |+
      -----BEGIN PRIVATE KEY-----
      MC4CAQAwBQYDK2VwBCIEIFdZWoDdFny5SMnP9Fyfr8bafi/B527EVZh8JJjDTIFO
      -----END PRIVATE KEY-----
    Public: |+
      -----BEGIN PUBLIC KEY-----
      MCowBQYDK2VwAyEAzpgjKSr9E032DX+foiOxq1QDsbzjLxagTN+yVpGWZB4=
      -----END PUBLIC KEY-----
  - ID: IRIS_AUTH_REFRESH
    Alg: EdDSA
    MaxAge: 720h
    Private: |+
      -----BEGIN PRIVATE KEY-----
      MC4CAQAwBQYDK2VwBCIEIHJ1aoIjA2sRp5eqGjGR3/UMucrHbBdBv9p8uwfzZ1KZ
      -----END PRIVATE KEY-----
    Public: |+
      -----BEGIN PUBLIC KEY-----
      MCowBQYDK2VwAyEAsKKAr+kDtfAqwG7cZdoEAfh9jHt9W8qi9ur5AA1KQAQ=
      -----END PUBLIC KEY-----
    EncryptionKey: 0123456789abcdef0123456789abcdef

You can also use the MustGenerateConfiguration function to generate a configuration file with random keys and ToYAML method to convert it to YAML format, this is useful for fast start when you don't know how to generate the necessary keys.

Although it's not yet implemented in a lot of old backends. Iris implemented custom support for EdDSA (Ed25519) which is a modern and secure elliptic-curve signature scheme that offers several advantages over traditional algorithms like RSA and ECDSA.

Pros of Ed25519 for Identity Servers:
Security Benefits:

Strong cryptography: Ed25519 provides 128-bit security level with only 256-bit keys
Resistance to side-channel attacks: More resistant to timing attacks compared to RSA
No parameter generation issues: Unlike RSA, no need to worry about weak key generation
Performance Benefits:

Fast signature verification: Much faster than RSA (especially RSA-2048+)
Small signature size: Only 64 bytes vs 256 bytes for RSA-2048
Small key size: 32-byte public keys vs 256+ bytes for RSA
Low memory footprint: Important for high-throughput identity servers
Modern Standards:

RFC 8037 compliant: Standardized for JWT/JWE usage
Future-proof: Designed to resist quantum computing threats better than RSA
package main

import (
    "os"

    "github.com/kataras/iris/v14/auth"
)

func main() {
    // Generate a new configuration file
    config := auth.MustGenerateConfiguration()
    yamlContents, err := config.ToYAML()
    if err != nil {
        panic(err)
    }

    // Save the configuration file
    err = os.WriteFile("./auth.yml", yamlContents, 0644)
    if err != nil {
        panic(err)
    }
}

Usage

Initializing the Auth Package

To initialize the auth package, you need to load the configuration file and create a new auth instance:

package main

import (
    "github.com/kataras/iris/v14"
    "github.com/kataras/iris/v14/auth"
)

func main() {
    app := iris.New()

    // Load configuration from a file
    authConfig, err := auth.LoadConfiguration("./auth.yml")
    if err != nil {
        panic(err)
    }

    // Initialize a new auth instance
    s, err := auth.New[User](authConfig)
    if err != nil {
        panic(err)
    }

    // Add a custom provider
    s.AddProvider(NewProvider())

    // Register routes
    app.Post("/signin", s.SigninHandler)
    app.Post("/refresh", s.RefreshHandler)
    app.Get("/signout", s.SignoutHandler)
    app.Get("/signout-all", s.SignoutAllHandler)

    app.Listen(":8080")
}
Custom User Type

You can define your own user type and implement the necessary methods for authentication and authorization:

package main

type AccessRole uint16

const (
    InvalidAccessRole AccessRole = 1 << iota
    Read
    Write
    Delete
    Owner  = Read | Write | Delete
    Member = Read | Write
)

type User struct {
    ID    string     `json:"id"`
    Email string     `json:"email"`
    Role  AccessRole `json:"role"`
}

func (u User) GetID() string {
    return u.ID
}

// Allow reports whether this role carries every bit of "role",
// so an Owner is allowed wherever a Member is.
func (r AccessRole) Allow(role AccessRole) bool {
    return r&role == role
}
Custom Provider

You can create a custom provider to handle user authentication and token validation:

package main

import (
    "context"
    "fmt"
    "sync"
    "time"

    "github.com/kataras/iris/v14/auth"
)

type Provider struct {
    dataset []User
    invalidated    map[string]struct{}
    invalidatedAll map[string]int64
    mu             sync.RWMutex
}

func NewProvider() *Provider {
    return &Provider{
        dataset: []User{
            {ID: "id-1", Email: "kataras2006@hotmail.com", Role: Owner},
            {ID: "id-2", Email: "example@example.com", Role: Member},
        },
        invalidated:    make(map[string]struct{}),
        invalidatedAll: make(map[string]int64),
    }
}

func (p *Provider) Signin(ctx context.Context, username, password string) (User, error) {
    for _, user := range p.dataset {
        if user.Email == username {
            return user, nil
        }
    }
    return User{}, fmt.Errorf("user not found")
}

// Refresh is called by the RefreshHandler with the user the token was issued
// for; reload it from storage so a changed role or email reaches the new token.
func (p *Provider) Refresh(ctx context.Context, u User) (User, error) {
    for _, user := range p.dataset {
        if user.ID == u.ID {
            return user, nil
        }
    }
    return User{}, fmt.Errorf("user not found")
}

func (p *Provider) ValidateToken(ctx context.Context, standardClaims auth.StandardClaims, u User) error {
    p.mu.RLock()
    _, tokenBlocked := p.invalidated[standardClaims.ID]
    if !tokenBlocked && standardClaims.OriginID != "" {
        _, tokenBlocked = p.invalidated[standardClaims.OriginID]
    }
    p.mu.RUnlock()

    if tokenBlocked {
        return fmt.Errorf("token was invalidated")
    }

    p.mu.RLock()
    ts, oldUserBlocked := p.invalidatedAll[u.ID]
    p.mu.RUnlock()

    if oldUserBlocked && standardClaims.IssuedAt <= ts {
        return fmt.Errorf("token was invalidated")
    }

    return nil
}

func (p *Provider) InvalidateToken(ctx context.Context, standardClaims auth.StandardClaims, u User) error {
    p.mu.Lock()
    p.invalidated[standardClaims.ID] = struct{}{}
    p.mu.Unlock()
    return nil
}

func (p *Provider) InvalidateTokens(ctx context.Context, u User) error {
    p.mu.Lock()
    p.invalidatedAll[u.ID] = time.Now().Unix()
    p.mu.Unlock()
    return nil
}
Custom Error Handler

You can customize the error handling by implementing the ErrorHandler interface and registering it with the Auth instance:

package main

import (
    "github.com/kataras/iris/v14/context"
    "github.com/kataras/iris/v14/rest/errors"
)

type CustomErrorHandler struct{}

func (e *CustomErrorHandler) InvalidArgument(ctx *context.Context, err error) {
    errors.InvalidArgument.Detail(ctx, "unable to parse body", err.Error())
}

func (e *CustomErrorHandler) Unauthenticated(ctx *context.Context, err error) {
    errors.Unauthenticated.Err(ctx, err)
}

To register the custom error handler:

s.SetErrorHandler(new(CustomErrorHandler))
Token Invalidation

You can invalidate tokens using the InvalidateToken and InvalidateTokens methods of the provider:

package main

// Invalidate a single token.
func (p *Provider) InvalidateToken(ctx context.Context, standardClaims auth.StandardClaims, u User) error {
    p.mu.Lock()
    p.invalidated[standardClaims.ID] = struct{}{}
    p.mu.Unlock()
    return nil
}

// Invalidate all tokens for this user.
func (p *Provider) InvalidateTokens(ctx context.Context, u User) error {
    p.mu.Lock()
    p.invalidatedAll[u.ID] = time.Now().Unix()
    p.mu.Unlock()
    return nil
}
VerifyHandler

The VerifyHandler method verifies and sets the necessary information about the user and the verified token to the Iris Context. You can use it to protect routes and allow access based on user roles:

package main

import (
    "context"
    "fmt"

    "github.com/kataras/iris/v14"
    "github.com/kataras/iris/v14/auth"
)

// allowRole rejects a verified user whose role does not include "role".
// AccessRole.Allow is defined next to the User type above.
func allowRole(role AccessRole) auth.VerifyUserFunc[User] {
    return func(ctx context.Context, u User) error {
        if !u.Role.Allow(role) {
            return fmt.Errorf("invalid role")
        }
        return nil
    }
}

func main() {
    app := iris.New()

    // Load configuration from a file
    authConfig, err := auth.LoadConfiguration("./auth.yml")
    if err != nil {
        panic(err)
    }

    // Initialize a new auth instance
    s, err := auth.New[User](authConfig)
    if err != nil {
        panic(err)
    }

    // Add a custom provider
    s.AddProvider(NewProvider())

    // Register routes
    app.Post("/signin", s.SigninHandler)
    app.Post("/refresh", s.RefreshHandler)
    app.Get("/signout", s.SignoutHandler)
    app.Get("/signout-all", s.SignoutAllHandler)

    // Protect routes with VerifyHandler
    app.Get("/member", s.VerifyHandler(allowRole(Member)), renderMemberPage(s))
    app.Get("/owner", s.VerifyHandler(allowRole(Owner)), renderOwnerPage(s))

    app.Listen(":8080")
}

func renderMemberPage(s *auth.Auth[User]) iris.Handler {
    return func(ctx iris.Context) {
        user := s.GetUser(ctx)
        ctx.Writef("Hello member: %s\n", user.Email)
    }
}

func renderOwnerPage(s *auth.Auth[User]) iris.Handler {
    return func(ctx iris.Context) {
        user := s.GetUser(ctx)
        ctx.Writef("Hello owner: %s\n", user.Email)
    }
}

Example

Here is a complete example of how to use the auth package in an Iris application:

package main

import (
    "github.com/kataras/iris/v14"
    "github.com/kataras/iris/v14/auth"
)

func main() {
    app := iris.New()

    // Load configuration from a file
    authConfig, err := auth.LoadConfiguration("./auth.yml")
    if err != nil {
        panic(err)
    }

    // Initialize a new auth instance
    s, err := auth.New[User](authConfig)
    if err != nil {
        panic(err)
    }

    // Add a custom provider
    s.AddProvider(NewProvider())

    // Optionally set a custom error handler
    s.SetErrorHandler(new(CustomErrorHandler))

    // Register routes
    app.Post("/signin", s.SigninHandler)
    app.Post("/refresh", s.RefreshHandler)
    app.Get("/signout", s.SignoutHandler)
    app.Get("/signout-all", s.SignoutAllHandler)

    // Protect routes with VerifyHandler
    app.Get("/member", s.VerifyHandler(allowRole(Member)), renderMemberPage(s))
    app.Get("/owner", s.VerifyHandler(allowRole(Owner)), renderOwnerPage(s))

    app.Listen(":8080")
}

func renderMemberPage(s *auth.Auth[User]) iris.Handler {
    return func(ctx iris.Context) {
        user := s.GetUser(ctx)
        ctx.Writef("Hello member: %s\n", user.Email)
    }
}

func renderOwnerPage(s *auth.Auth[User]) iris.Handler {
    return func(ctx iris.Context) {
        user := s.GetUser(ctx)
        ctx.Writef("Hello owner: %s\n", user.Email)
    }
}

Documentation

Overview

Package auth provides generic, token-based authentication for Iris applications.

The central type is Auth[T], which signs and verifies JSON Web Tokens for a user type T through pluggable Provider implementations. It supports access and refresh tokens with rotation, optional secure-cookie storage, and ready-made HTTP handlers for the sign-in, verify, refresh and sign-out flows (SigninHandler, VerifyHandler, RefreshHandler, SignoutHandler).

The auth/identity subpackage builds a full user-management service on top of this package, and auth/oauth2 implements an OAuth2 authorization server.

Index

Constants

View Source
const (
	// The JWT Key ID for access tokens.
	KIDAccess = "IRIS_AUTH_ACCESS"
	// The JWT Key ID for refresh tokens.
	KIDRefresh = "IRIS_AUTH_REFRESH"
)

Variables

View Source
var ErrMissingUser = stdErrors.New("auth: no verified user of the expected type on the request")

ErrMissingUser is the reason of the 401 that Scope answers when the Context carries no verified user of the type Scope derives from: either no VerifyHandler ran in front of it, or it verified a different user type.

View Source
var ErrNoProvider = fmt.Errorf("auth: no provider registered")

ErrNoProvider is returned when no provider is registered to an Auth of T instance.

Functions

func AccessTokenOption

func AccessTokenOption(opts ...jwt.SignOption) jwt.SignOption

AccessTokenOption returns a jwt.SignOptionFunc which can be used to apply options only to the access token's key. It checks the OriginID field of the claims, if it's empty then it applies the options to the access token's key, otherwise it does nothing.

func GetToken

func GetToken(ctx *context.Context) (*jwt.VerifiedToken, bool)

GetToken accepts the iris Context and returns the verified JWT token instance, which contains the raw access token and its claims. It's only available after Auth.VerifyHandler is executed.

func GetUser

func GetUser[T User](ctx *context.Context) T

GetUser is the package-level function of the Auth.GetUser method. It returns the T user value after Auth.VerifyHandler is executed.

func RefreshTokenOption

func RefreshTokenOption(opts ...jwt.SignOption) jwt.SignOption

RefreshTokenOption returns a jwt.SignOptionFunc which can be used to apply options only to the refresh token's key.

func Scope

func Scope[User any, ID comparable](derive func(User) ID) context.Handler

Scope derives a per-request scope id (a tenant, a customer, an organisation) from the authenticated user once, after VerifyHandler, and stores it on the Context for every handler and query after it.

It exists so that the scope is derived in one place instead of in every handler: a handler that forgets to filter by tenant is a data leak, and a handler that derives it again is a second chance to get it wrong.

A missing user answers 401, the same failure VerifyHandler answers with, because a scope cannot be derived without one. So does a user of another type: reading it untyped and deriving from the zero value would answer 200 with an empty scope, which is a cross-tenant read wearing the disguise of the next paragraph.

A derived zero id is allowed and stored as it is: a global administrator may legitimately have no scope, and that is not an authentication failure. Guard those requests by checking the id in the handler, not by relying on Scope.

The cost per request is one Values read, the derive call and one Values set; ScopeID is one map lookup and one type assertion. No reflection is involved.

Usage:

app.Use(a.VerifyHandler(), auth.Scope(func(u Customer) string {
	return u.TenantID
}))

// ...in a handler, or in an mvc.BeforeWrite hook:
tenantID, ok := auth.ScopeID[string](ctx)

func ScopeID

func ScopeID[ID comparable](ctx *context.Context) (ID, bool)

ScopeID returns the id Scope stored on the Context. It reports false when Scope did not run or when it stored an id of another type, so that a zero id a caller must not trust cannot be mistaken for a real one.

func UserAuthorized

func UserAuthorized(ctx *context.Context) bool

UserAuthorized accepts the iris Context and returns true if the user is authorized.

Types

type Auth

type Auth[T User] struct {

	// Always not nil, set to custom error handler on SetErrorHandler.
	ErrorHandler ErrorHandler

	// The registered validators for the token.
	// They are called in the order they are registered.
	// The first one that returns an error will stop the validation process.
	//
	// See `s.verify`.
	Validators []jwt.TokenValidatorFunc
	// contains filtered or unexported fields
}

Auth holds the necessary functionality to authorize and optionally authenticating users to access and perform actions against the resource server (Iris API). It completes a secure and fast JSON Web Token signer and verifier which, based on the custom application needs, can be further customized. Each Auth of T instance can sign and verify a single custom <T> instance, more Auth instances can share the same configuration to support multiple custom user types. Initialize a new Auth of T instance using the New or MustLoad package-level functions. Most important methods of the instance are: - AddProvider - SigninHandler - VerifyHandler - SignoutHandler - SignoutAllHandler

Example can be found at: https://github.com/kataras/iris/tree/main/_examples/09-authentication/auth-sdk/main.go.

func Get

func Get[T User](ctx *context.Context) (*Auth[T], bool)

Get accepts the iris Context and returns the current Auth[T] instance. It's only available after Auth.VerifyHandler is executed.

func Must

func Must[T User](config Configuration) *Auth[T]

Must calls New with the same configuration and panics if it returns an error. It takes what New takes and is intended for variable initializations such as

var s = auth.Must[MyUser](config)

func MustLoad

func MustLoad[T User](filename string) *Auth[T]

MustLoad binds a filename (fullpath) configuration yaml or json and constructs a new Auth instance. It panics on error.

func New

func New[T User](config Configuration) (*Auth[T], error)

New initializes a new Auth instance typeof T and returns it. The T generic can be any custom struct. It accepts a Configuration value which can be constructed manually or through a configuration file using the MustGenerateConfiguration or MustLoadConfiguration or LoadConfiguration or MustLoad package-level functions.

Example can be found at: https://github.com/kataras/iris/tree/main/_examples/09-authentication/auth-sdk/main.go.

func Resolve

func Resolve[T User]() (*Auth[T], bool)

Resolve tries to return the Auth of T instance based on the type of T.

func (*Auth[T]) AddProvider

func (s *Auth[T]) AddProvider(providers ...Provider[T]) *Auth[T]

AddProvider registers one or more providers to this Auth of T instance and returns itself. Look the Provider godoc for more.

func (*Auth[Original]) Clone

func (a *Auth[Original]) Clone[New User]() *Auth[New]

Clone returns a new Auth instance sharing this one's configuration, keys and cookie transcoder but typed for a different User claims type. Useful when one keypair authenticates more than one account shape.

It could not exist before Go 1.27: the New claims type is independent of the receiver's type parameter, which only a generic method can express.

func (*Auth[T]) Config

func (s *Auth[T]) Config() Configuration

Config returns the configuration of this Auth of T instance.

func (*Auth[T]) ExtractAccessToken

func (s *Auth[T]) ExtractAccessToken(ctx *context.Context) string

ExtractAccessToken extracts the access token from the request's header or cookie.

func (*Auth[T]) GetUser

func (s *Auth[T]) GetUser(ctx *context.Context) T

GetUser accepts the iris Context and returns the T custom user/claims struct value. It's only available after Auth.VerifyHandler is executed.

func (*Auth[T]) JWKSHandler

func (s *Auth[T]) JWKSHandler() context.Handler

JWKSHandler returns a handler that can be used to expose the JSON Web Key Set (JWKS) of the Auth instance. The JWKS is a JSON object that represents a set of JWKs.

See https://tools.ietf.org/html/rfc7517#section-5 for more.

Example:

app.Get("/.well-known/jwks.json", AuthInstance.JWKSHandler())

func (*Auth[T]) Keys

func (s *Auth[T]) Keys() jwt.Keys

Keys returns the keys loaded by the keys configuration of this Auth of T instance.

func (*Auth[T]) Refresh

func (s *Auth[T]) Refresh(ctx stdContext.Context, refreshToken []byte) (*oauth2.Token, error)

Refresh accepts a previously generated refresh token (from SigninHandler) and returns a new access and refresh token pair.

func (*Auth[T]) RefreshHandler

func (s *Auth[T]) RefreshHandler(ctx *context.Context)

RefreshHandler reads the request body which should include data for `RefreshRequest` structure and sends a new access and refresh token pair, also sets the cookie to the new encrypted access token value. See `Refresh` method for more.

func (*Auth[T]) RefreshProvider

func (s *Auth[T]) RefreshProvider(ctx stdContext.Context, t T) (T, error)

RefreshProvider calls the registered providers to refresh the user information based on the provided custom T value. It returns the updated T value or an error if no provider was registered or if all providers errored.

func (*Auth[T]) SetErrorHandler

func (s *Auth[T]) SetErrorHandler(errHandler ErrorHandler) *Auth[T]

SetErrorHandler sets a custom error handler to this Auth of T instance and returns itself. Look the Provider and ErrorHandler godoc for more.

func (*Auth[T]) SetTransformer

func (s *Auth[T]) SetTransformer(transformer Transformer[T]) *Auth[T]

SetTransformer sets a custom transformer to this Auth of T instance and returns itself. Look the Provider and Transformer godoc for more.

func (*Auth[T]) SetTransformerFunc

func (s *Auth[T]) SetTransformerFunc(transfermerFunc func(ctx stdContext.Context, tok *VerifiedToken) (T, error)) *Auth[T]

SetTransformerFunc like SetTransformer method but accepts a function instead.

func (*Auth[T]) SetValidators

func (s *Auth[T]) SetValidators(validators ...jwt.TokenValidatorFunc) *Auth[T]

SetValidators appends the given custom validators to this Auth of T instance and returns itself. Repeated calls accumulate; set the exported Validators field directly to replace or clear them.

func (*Auth[T]) SignToken

func (s *Auth[T]) SignToken(t any, opts ...jwt.SignOption) (*oauth2.Token, error)

SignToken signs a token based on the provided custom T value and returns a pair of access and refresh tokens.

func (*Auth[T]) Signin

func (s *Auth[T]) Signin(ctx stdContext.Context, username, password string) (*oauth2.Token, error)

Signin signs a token based on the provided username and password and returns a pair of access and refresh tokens.

Signin calls the Provider.Signin method to check if a user is authenticated by the given username and password combination.

func (*Auth[T]) SigninHandler

func (s *Auth[T]) SigninHandler(ctx *context.Context)

SigninHandler generates and sends a pair of access and refresh token to the client as JSON body of `oauth2.Token` and cookie (if cookie setting was provided). If a safe, same-site relative "redirect_to" (or "redirect_uri") query parameter is present, it redirects there instead of writing the JSON body. See `Signin` method for more.

func (*Auth[T]) SigninProvider

func (s *Auth[T]) SigninProvider(ctx stdContext.Context, username, password string) (T, error)

SigninProvider verifies the username and password against the registered providers and returns the custom T value.

func (*Auth[T]) Signout

func (s *Auth[T]) Signout(ctx stdContext.Context, token []byte, all bool) error

Signout accepts the access token and a boolean which reports whether the signout should be applied to all tokens generated for a specific user (logout from all devices) or just the provided token's one. It calls the Provider's InvalidateToken(all=false) or InvalidateTokens (all=true).

func (*Auth[T]) SignoutAllHandler

func (s *Auth[T]) SignoutAllHandler(ctx *context.Context)

SignoutAllHandler verifies the request's access token and should invalidate all the tokens generated previously calling the Provider's InvalidateTokens method. See `Signout` method too.

func (*Auth[T]) SignoutHandler

func (s *Auth[T]) SignoutHandler(ctx *context.Context)

SignoutHandler verifies the request's access token and invalidates it, calling the Provider's InvalidateToken method. See `Signout` method too.

func (*Auth[T]) Verify

func (s *Auth[T]) Verify(ctx stdContext.Context, token []byte, verifyFuncs ...VerifyUserFunc[T]) (T, *VerifiedToken, error)

Verify accepts a token and verifies it. It returns the token's custom claims and the verified token information.

func (*Auth[Original]) VerifyExtra

func (a *Auth[Original]) VerifyExtra[New User](ctx stdContext.Context, token []byte, verifyFuncs ...VerifyUserFunc[New]) (Original, New, *VerifiedToken, error)

VerifyExtra verifies a token like Verify and additionally decodes and optionally validates a second, independent claims value of type New.

func (*Auth[T]) VerifyHandler

func (s *Auth[T]) VerifyHandler(verifyFuncs ...VerifyUserFunc[T]) context.Handler

VerifyHandler verifies and sets the necessary information about the user(claims) and the verified token to the Iris Context and calls the Context's Next method. This information is available through auth.GetToken and auth.GetUser[T] package-level functions.

See `Verify` method for more.

func (*Auth[T]) WithProvider

func (s *Auth[T]) WithProvider(provider Provider[T]) *Auth[T]

WithProvider registers a provider (if not nil) and returns this "s" Auth instance.

func (*Auth[T]) WithProviderAndErrorHandler

func (s *Auth[T]) WithProviderAndErrorHandler(provider Provider[T], errHandler ErrorHandler) *Auth[T]

WithProviderAndErrorHandler registers a provider (if not nil) and an error handler (if not nil) and returns this "s" Auth instance. Unlike AddProvider, which appends, it replaces any previously registered providers with the given one, then it sets the error handler as SetErrorHandler does. It's really useful when registering an Auth instance using the iris.Router.Controller method when a Provider of T and ErrorHandler is available through the registered Router's dependencies.

Usage Example:

api := app.Router("/api")
api.RegisterDependency(
  NewAuthProviderErrorHandler(),
  NewAuthCustomerProvider,
  auth.Must[Customer](authConfig).WithProviderAndErrorHandler,
)

type ClaimsProvider

type ClaimsProvider interface {
	GetAccessTokenClaims() StandardClaims
	GetRefreshTokenClaims(accessClaims StandardClaims) StandardClaims
}

ClaimsProvider is an optional interface, which may not be used at all. If implemented by a Provider, it signs the jwt token using these claims to each of the following token types.

type Configuration

type Configuration struct {
	// The authorization header keys that server should read the access token from.
	//
	// Required, there is no default value, the `New` function
	// returns an error when this field is empty.
	// The `Configuration.BindRandom` method and the
	// `MustGenerateConfiguration` package-level function fill it with:
	// - Authorization
	// - X-Authorization
	Headers []string `json:"headers" yaml:"Headers" toml:"Headers" ini:"Headers"`
	// HeadersNoBearer if true then the server will not expect the "Bearer " prefix
	// before the values of the given "Headers".
	// Defaults to false.
	HeadersNoBearer bool `json:"headers_no_bearer" yaml:"HeadersNoBearer" toml:"HeadersNoBearer" ini:"HeadersNoBearer"`
	// Cookie optional configuration.
	// A Cookie.Name holds the access token value fully encrypted.
	Cookie CookieConfiguration `json:"cookie" yaml:"Cookie" toml:"Cookie" ini:"cookie"`
	// Keys MUST define the jwt keys configuration for access,
	// and optionally, for refresh tokens signing and verification.
	Keys jwt.KeysConfiguration `json:"keys" yaml:"Keys" toml:"Keys" ini:"keys"`
}

Configuration holds the necessary information for Iris Auth & Single-Sign-On feature.

See the `New` package-level function.

func LoadConfiguration

func LoadConfiguration(filename string) (c Configuration, err error)

LoadConfiguration reads a filename (fullpath) and returns a Configuration binded to the contents of the given filename. See Configuration.BindFile method too.

Example yaml contents:

Headers: # required.

  • "Authorization"
  • "X-Authorization"

Cookie: # optional.

Name: "iris_auth_cookie"
Secure: false
Hash: "D*G-KaPdSgUkXp2s5v8y/B?E(H+MbQeThWmYq3t6w9z$C&F)J@NcRfUjXn2r4u7x" # length of 64 characters (512-bit).
Block: "VkYp3s6v9y$B&E)H@McQfTjWmZq4t7w!" # length of 32 characters (256-bit).

Keys:

  • ID: IRIS_AUTH_ACCESS # required. Alg: EdDSA MaxAge: 2h # 2 hours lifetime for access tokens. Private: |+ -----BEGIN PRIVATE KEY----- MC4CAQAwBQYDK2VwBCIEIFdZWoDdFny5SMnP9Fyfr8bafi/B527EVZh8JJjDTIFO -----END PRIVATE KEY----- Public: |+ -----BEGIN PUBLIC KEY----- MCowBQYDK2VwAyEAzpgjKSr9E032DX+foiOxq1QDsbzjLxagTN+yVpGWZB4= -----END PUBLIC KEY-----
  • ID: IRIS_AUTH_REFRESH # optional. Good practise to have it though. Alg: EdDSA # 1 month lifetime for refresh tokens, # after that period the user has to signin again. MaxAge: 720h Private: |+ -----BEGIN PRIVATE KEY----- MC4CAQAwBQYDK2VwBCIEIHJ1aoIjA2sRp5eqGjGR3/UMucrHbBdBv9p8uwfzZ1KZ -----END PRIVATE KEY----- Public: |+ -----BEGIN PUBLIC KEY----- MCowBQYDK2VwAyEAsKKAr+kDtfAqwG7cZdoEAfh9jHt9W8qi9ur5AA1KQAQ= -----END PUBLIC KEY----- # Example of setting a binary form of the encryption key for refresh tokens, # it could be a "string" as well. EncryptionKey: 0123456789abcdef0123456789abcdef

func MustGenerateConfiguration

func MustGenerateConfiguration() (c Configuration)

MustGenerateConfiguration calls the Configuration's BindRandom method and returns the result. It panics on errors.

func MustLoadConfiguration

func MustLoadConfiguration(filename string) Configuration

MustLoadConfiguration same as LoadConfiguration package-level function but it panics on error.

func (*Configuration) BindFile

func (c *Configuration) BindFile(filename string) error

BindFile binds a filename (fullpath) to "c" Configuration. The file format is either JSON or YAML and it should be suffixed with .json or .yml/.yaml.

func (*Configuration) BindRandom

func (c *Configuration) BindRandom() error

BindRandom binds the "c" configuration to random values for keys and cookie security. Keys will not be persisted between restarts, a more persistent storage should be considered for production applications, see BindFile method and LoadConfiguration/MustLoadConfiguration package-level functions.

func (*Configuration) Clone

func (c *Configuration) Clone() Configuration

Clone returns a deep copy of the Configuration.

func (*Configuration) ToJSON

func (c *Configuration) ToJSON() ([]byte, error)

ToJSON returns the "c" Configuration's contents as raw json byte slice.

func (*Configuration) ToYAML

func (c *Configuration) ToYAML() ([]byte, error)

ToYAML returns the "c" Configuration's contents as raw yaml byte slice.

type CookieConfiguration

type CookieConfiguration struct {
	// Name defines the cookie's name.
	Name string `json:"cookie" yaml:"Name" toml:"Name" ini:"name"`
	// Secure if true then "; Secure" is appended to the Set-Cookie header.
	// By setting the secure to true, the web browser will prevent the
	// transmission of a cookie over an unencrypted channel.
	//
	// Defaults to false but it's true when the request is under iris.Context.IsSSL().
	Secure bool `json:"secure" yaml:"Secure" toml:"Secure" ini:"secure"`
	// Hash is optional, it is used to authenticate cookie value using HMAC.
	// It is recommended to use a key with 32 or 64 bytes.
	Hash string `json:"hash" yaml:"Hash" toml:"Hash" ini:"hash"`
	// Block is optional, used to encrypt cookie value.
	// The key length must correspond to the block size
	// of the encryption algorithm. For AES, used by default, valid lengths are
	// 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.
	Block string `json:"block" yaml:"Block" toml:"Block" ini:"block"`
}

CookieConfiguration holds the necessary information for cookie client storage.

type DefaultErrorHandler

type DefaultErrorHandler struct{}

DefaultErrorHandler is the default registered ErrorHandler which can be replaced through the Auth.SetErrorHandler method.

func (*DefaultErrorHandler) InvalidArgument

func (e *DefaultErrorHandler) InvalidArgument(ctx *context.Context, err error)

InvalidArgument sends 400 (bad request) with "unable to parse body" as its message and the "err" value as its details.

func (*DefaultErrorHandler) Unauthenticated

func (e *DefaultErrorHandler) Unauthenticated(ctx *context.Context, err error)

Unauthenticated sends 401 (unauthenticated) with the "err" value as its message.

type ErrorHandler

type ErrorHandler interface {
	// InvalidArgument should handle any 400 (bad request) errors,
	// e.g. invalid request body.
	InvalidArgument(ctx *context.Context, err error)
	// Unauthenticated should handle any 401 (unauthenticated) errors,
	// e.g. user not found or invalid credentials.
	Unauthenticated(ctx *context.Context, err error)
}

ErrorHandler is an optional interface which can be implemented by a Provider as well.

ErrorHandler is the interface which controls the HTTP errors on Auth.SigninHandler, Auth.VerifyHandler, Auth.SignoutHandler and Auth.SignoutAllHandler handelrs.

type Provider

type Provider[T User] interface {
	// Signin accepts a username (or email) and a password and should
	// return a valid T value or an error describing
	// the user authentication or verification reason of failure.
	//
	// The first input argument standard context can be
	// casted to iris.Context if executed through Auth.SigninHandler.
	//
	// It's called on Auth.SigninHandler.
	Signin(ctx stdContext.Context, username, password string) (T, error)

	// Refresh accepts the T value obtained by the Signin method
	// and should return a new T value or an error describing
	// the user authentication or verification reason of failure.
	// It is mostly used to refresh the user information from a persistence storage.
	// The first input argument standard context can be
	// casted to iris.Context if executed through Auth.RefreshHandler.
	//
	// It's called on Auth.RefreshHandler.
	Refresh(ctx stdContext.Context, t T) (T, error)

	// ValidateToken accepts the standard JWT claims and the T value obtained
	// by the Signin method and should return a nil error on validation success
	// or a non-nil error for validation failure.
	// It is mostly used to perform checks of the T value's struct fields or
	// the standard claim's (e.g. origin jwt token id).
	// It can be an empty method too which returns a nil error.
	//
	// The first input argument standard context can be
	// casted to iris.Context if executed through Auth.VerifyHandler.
	//
	// It's caleld on Auth.VerifyHandler.
	ValidateToken(ctx stdContext.Context, standardClaims StandardClaims, t T) error

	// InvalidateToken is optional and can be used to allow tokens to be invalidated
	// from server-side. Commonly, implement when a token and user pair is saved
	// on a persistence storage and server can decide which token is valid or invalid.
	// It can be an empty method too which returns a nil error.
	//
	// The first input argument standard context can be
	// casted to iris.Context if executed through Auth.SignoutHandler.
	//
	// It's called on Auth.SignoutHandler.
	InvalidateToken(ctx stdContext.Context, standardClaims StandardClaims, t T) error
	// InvalidateTokens is like InvalidateToken but it should invalidate
	// all tokens generated for a specific T value.
	// It can be an empty method too which returns a nil error.
	//
	// The first input argument standard context can be
	// casted to iris.Context if executed through Auth.SignoutAllHandler.
	//
	// It's called on Auth.SignoutAllHandler.
	InvalidateTokens(ctx stdContext.Context, t T) error
}

Provider is an interface of T which MUST be completed by a custom value type to provide user information to the Auth's JWT Token Signer and Verifier.

A provider can optionally complete the Transformer, ClaimsProvider and ErrorHandler all in once when necessary. Set a provider using the AddProvider method of Auth type.

Example can be found at: https://github.com/kataras/iris/tree/main/_examples/09-authentication/auth-sdk/main.go (customerProvider).

type RefreshRequest

type RefreshRequest struct {
	RefreshToken string `json:"refresh_token"`
}

RefreshRequest is the request body the server expects on RefreshHandler to renew an access and refresh token pair.

type SigninRequest

type SigninRequest struct {
	Username string `json:"username" form:"username,omitempty"` // username OR email, username has priority over email.
	Email    string `json:"email" form:"email,omitempty"`       // email OR username.
	Password string `json:"password" form:"password"`
}

SigninRequest is the request body the server expects on SigninHandler. The Password and Username or Email should be filled.

type StandardClaims

type StandardClaims = jwt.Claims

StandardClaims is an alias of jwt.Claims, it holds the standard JWT claims.

type Transformer

type Transformer[T User] interface {
	Transform(ctx stdContext.Context, tok *VerifiedToken) (T, error)
}

Transformer is an optional interface which can be implemented by a Provider as well. Set a Transformer through Auth.SetTransformer or Auth.SetTransformerFunc or by implementing the Transform method inside a Provider which can be registered through the Auth.AddProvider method.

A transformer is called on Auth.VerifyHandler before Provider.ValidateToken and it can be used to modify the T value based on the token's contents. It is mostly used to convert the json claims to T value manually, when they differ.

The first input argument standard context can be casted to iris.Context if executed through Auth.VerifyHandler.

type TransformerFunc

type TransformerFunc[T User] func(ctx stdContext.Context, tok *VerifiedToken) (T, error)

TransformerFunc completes the Transformer interface.

func (TransformerFunc[T]) Transform

func (fn TransformerFunc[T]) Transform(ctx stdContext.Context, tok *VerifiedToken) (T, error)

Transform calls itself.

type User

type User = any

User is an alias of an empty interface, it's here to declare the typeof T, which can be any custom struct type.

Example can be found at: https://github.com/kataras/iris/tree/main/_examples/09-authentication/auth-sdk/main.go (Customer).

type VerifiedToken

type VerifiedToken = jwt.VerifiedToken

VerifiedToken holds the information about a verified token.

type VerifyUserFunc

type VerifyUserFunc[T User] func(ctx stdContext.Context, t T) error

VerifyUserFunc is passed on Verify and VerifyHandler method to, optionally, further validate a T user value.

Directories

Path Synopsis
_example command
sdk
Package oauth2 provides an implementation of OAuth2 server-related logic, including the registration and retrieval of clients, authorization codes, device codes, tokens, and consent handling.
Package oauth2 provides an implementation of OAuth2 server-related logic, including the registration and retrieval of clients, authorization codes, device codes, tokens, and consent handling.
opa
Open Policy Agent (OPA) is an open-source, general-purpose policy engine that enables unified, context-aware policy enforcement across the stack.
Open Policy Agent (OPA) is an open-source, general-purpose policy engine that enables unified, context-aware policy enforcement across the stack.

Jump to

Keyboard shortcuts

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