auth

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2026 License: MIT Imports: 13 Imported by: 0

README

api-auth-client

The api-auth-client repository provides convenience methods for interacting with the api-auth server for token creation and validation.

Installation

go get github.com/Dallin-Cawley/api-auth-client

Initialization

To use this library, you first need to initialize the configuration with the base URL of your api-auth server and a credentials loader. You can also optionally provide a custom logger.

package main

import (
    "github.com/Dallin-Cawley/api-auth-client"
)

func init() {
    err := auth.Init(
        auth.WithBaseURL("https://auth.your-server.com"),
        auth.WithLoader(auth.NewEnvLoader()),
    )
    if err != nil {
        panic(err)
    }
}
Setting a Custom Logger

By default, the library uses a JSON handler logging to os.Stdout at Debug level. You can override this:

package main

import (
    "log/slog"
    "os"
    "github.com/Dallin-Cawley/api-auth-client"
)

err := auth.Init(
    auth.WithBaseURL("https://auth.your-server.com"),
    auth.WithLoader(auth.NewFileLoader(auth.WithFilePath("credentials.json"))),
    auth.WithLogger(slog.New(slog.NewTextHandler(os.Stderr, nil))),
)

Usage

Token Creation

To create a new token, use the GetToken method. The credentials must have been loaded during initialization.

package main

import (
    "fmt"
    "github.com/Dallin-Cawley/api-auth-client"
)

func main() {
    token, err := auth.GetToken()
    if err != nil {
        panic(err)
    }

    fmt.Printf("Access Token: %s\n", token.AccessToken)
}
Token Validation

To verify an existing token, use the VerifyToken method.

package main

import (
    "fmt"
    "github.com/Dallin-Cawley/api-auth-client"
)

func validate(accessToken string) {
    result, err := auth.VerifyToken(accessToken)
    if err != nil {
        fmt.Println("Token is invalid:", err)
        return
    }

    fmt.Printf("Token is valid for subject: %s\n", result.Subject)
}
Request Decoration

For automatic token management and request decoration, use the ClientCredentialsDecorator. It handles token caching and automatic refreshing when the token expires. The decorator is thread-safe and can be shared across multiple clients or goroutines.

package main

import (
    "net/http"
    "github.com/Dallin-Cawley/api-auth-client"
)

func main() {
    decorator := auth.NewClientCredentialsDecorator("my-client-id", "my-client-secret")

    req, _ := http.NewRequest("GET", "https://api.your-service.com/data", nil)
    
    // Decorate the request with a Bearer token
    if err := decorator.Decorate(req); err != nil {
        panic(err)
    }

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
    
    // ...
}
Auth Middleware

The library also provides a standard library-compatible middleware for authenticating incoming HTTP requests.

package main

import (
    "fmt"
    "net/http"
    "github.com/Dallin-Cawley/api-auth-client"
)

func main() {
    mux := http.NewServeMux()

    // Protected endpoint
    mux.Handle("GET /protected", auth.Middleware(http.HandlerFunc(protectedHandler)))

    http.ListenAndServe(":8080", mux)
}

func protectedHandler(w http.ResponseWriter, r *http.Request) {
    // Retrieve token information from the context
    tokenInfo, ok := auth.FromContext(r.Context())
    if !ok {
        http.Error(w, "Unauthorized", http.StatusUnauthorized)
        return
    }

    fmt.Fprintf(w, "Hello, %s!", tokenInfo.Subject)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FromContext

func FromContext(ctx context.Context) (*output.ValidateOutputBody, bool)

FromContext returns the token information from the request context.

func GetToken

func GetToken() (*output.CreateTokenOutputBody, error)

GetToken requests a new access token from the api-auth server using the provided credentials.

func Init

func Init(opts ...Option) error

Init initializes the global configuration for the auth package with the provided options.

func Middleware

func Middleware(next http.Handler) http.Handler

Middleware is a middleware that authenticates incoming requests using a Bearer token. It validates the token against the api-auth server using VerifyToken.

func VerifyToken

func VerifyToken(token string) (*output.ValidateOutputBody, error)

VerifyToken validates an access token with the api-auth server.

Types

type ClientCredentialsDecorator

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

ClientCredentialsDecorator implements the Decorator interface using the OAuth 2.0 Client Credentials flow.

func NewClientCredentialsDecorator

func NewClientCredentialsDecorator(clientID, clientSecret string) *ClientCredentialsDecorator

NewClientCredentialsDecorator creates a new instance of ClientCredentialsDecorator.

func (*ClientCredentialsDecorator) Decorate

func (decorator *ClientCredentialsDecorator) Decorate(r *http.Request) error

Decorate adds a Bearer token to the Authorization header of the provided HTTP request. It refreshes the token if it is missing or expired.

type Config

type Config struct {
	BaseURL     string
	Credentials *Credentials
	Logger      *slog.Logger
	CredLoader  Loader
}

type Credentials

type Credentials struct {
	ClientID     string `json:"client_id"`
	ClientSecret string `json:"client_secret"`
}

func NewCredentials

func NewCredentials(clientID, clientSecret string) *Credentials

type Decorator

type Decorator interface {
	// Decorate adds authorization to the provided HTTP request.
	Decorate(r *http.Request) error
}

Decorator is an interface that defines the Decorate method for adding authorization to an HTTP request.

type ErrMissingRequiredConfig

type ErrMissingRequiredConfig struct {
	Field string
}

ErrMissingRequiredConfig is returned when a required configuration field is missing during initialization.

func (*ErrMissingRequiredConfig) Error

func (err *ErrMissingRequiredConfig) Error() string

type Loader

type Loader interface {
	Load() (*Credentials, error)
}

type Option

type Option func(*Config)

Option defines a functional option for configuring the auth package.

func WithBaseURL

func WithBaseURL(url string) Option

WithBaseURL sets the base URL for the api-auth server.

func WithLoader

func WithLoader(l Loader) Option

WithLoader sets the loader to be used for loading credentials.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger sets the logger to be used by the package.

Jump to

Keyboard shortcuts

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