oidcauth

package module
v0.0.0-...-0048abb Latest Latest
Warning

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

Go to latest
Published: Jun 28, 2022 License: MIT Imports: 9 Imported by: 0

README

oidc-auth

Go Reference Unit Test Status

Drop-in OIDC authentication support.

LICENSE

MIT

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrUnauthenticated = fmt.Errorf("unauthenticated")
	ErrMissingClaim    = fmt.Errorf("missing claim")
)

Functions

This section is empty.

Types

type ClaimsPrincipal

type ClaimsPrincipal interface {
	// Name returns the unique identity name of the principal.
	Name() string

	// HasRole checks if the principal has specified role.
	HasRole(role string) bool

	// Claims returns the claims from the token.
	Claims() MapClaims

	// BindClaims binds the token claims to given value receiver.
	BindClaims(v interface{}) error

	// AuthenticateErr returns error if the principal is unauthenticated.
	AuthenticateErr() error
}

ClaimsPrincipal defines the principal object.

func PrincipalFromHTTPRequest

func PrincipalFromHTTPRequest(req *http.Request) ClaimsPrincipal

PrincipalFromHTTPRequest retrieves the ClaimsPrincipal from the request. It returns unauthenticated principal if the request has not set.

type HTTPMiddleware

type HTTPMiddleware func(http.Handler) http.Handler

HTTPMiddleware is the middleware for HTTP handler.

func InterceptHTTP

func InterceptHTTP(params HTTPParams) HTTPMiddleware

InterceptHTTP creates a HTTP middleware for authenticating OIDC JWT token from the request.

type HTTPParams

type HTTPParams struct {
	Params

	// HTTPHeaderName specifies the header name for retrieving the token.
	// Defaults to `Authorization`.
	HTTPHeaderName string

	// HTTPHeaderPrefix specifies the prefix for the header name.
	// Defaults to `Bearer`.
	HTTPHeaderValuePrefix string
}

HTTPParams specifies the OIDC authentication settings for HTTP interceptor.

Example
package main

import (
	"fmt"
	"net/http"

	"github.com/b4fun/oidcauth"
)

func main() {
	params := oidcauth.HTTPParams{
		Params: oidcauth.Params{
			IssuerURL:     "https://accounts.google.com",
			ClientID:      "test-client",
			UserNameClaim: "sub",
			RolesClaim:    "roles",
		},
	}

	httpHandler := oidcauth.InterceptHTTP(params)(
		http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			principal := oidcauth.PrincipalFromHTTPRequest(r)

			err := principal.AuthenticateErr()
			fmt.Printf("authenticate err: %s", err)
		}),
	)

	httpServer := &http.Server{
		Addr:    ":8080",
		Handler: httpHandler,
	}
	go func() {
		httpServer.ListenAndServe()
	}()

	req, err := http.NewRequest("GET", "http://localhost:8080", nil)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJpc3N1ZXIiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20ifQ.Rp01XsySaZ8PAnSxG6oGeVol_fBnnQBWfSEnM91tHfc")
	// uncomment to start the request
	// http.DefaultClient.Do(req)
}
Output:

type MapClaims

type MapClaims map[string]interface{}

MapClaims represents a set of claims in the token.

type Params

type Params struct {
	// IssuerURL specifies the issuer URL for discovering public signing keys.
	// Only URLs which use the `https://` scheme are accepted. Required.
	IssuerURL string

	// ClientID specifies the client ID for the OIDC client. Required.
	ClientID string

	// UserNameClaim specifies the JWT claim to use as the user name.
	// By default `sub`, which is expected to the be a unique identifier
	// of the end user. Optional.
	UserNameClaim string

	// RolesClaim specifies the JWT claim to use as the user roles.
	// If the clam is present it must be an array of strings.
	RolesClaim string

	// RequiredClaims specifies a group of required claims in the ID token.
	// Optional.
	RequiredClaims map[string]string

	// CAFile specifies the full path to the CA that singed the identity provider's
	// web certificate. Defaults to the host's root CAs.
	CAFile string
}

Params specifies the OIDC authentication settings.

type PrincipalLoaderFunc

type PrincipalLoaderFunc func(ctx context.Context, token string) ClaimsPrincipal

PrincipalLoaderFunc loads a ClaimsPrincipal from given context and token.

func CreatePrincipalLoader

func CreatePrincipalLoader(params Params) (PrincipalLoaderFunc, error)

CreatePrincipalLoader creates the PrincipalLoaderFunc from the given Params.

Jump to

Keyboard shortcuts

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