samlsp

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: BSD-2-Clause Imports: 32 Imported by: 277 modules, 258 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package samlsp provides helpers that can be used to protect web services using SAML.

Example (Attributes)

This example shows how a handler wrapped by Middleware.RequireAccount reads the user's identity from the SAML assertion.

The default session (a JWTSessionClaims) keeps the assertion's Subject NameID as the JWT subject and each attribute under its FriendlyName, or its Name when there is no FriendlyName. Which attributes are present, and what they are called, is up to the identity provider.

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/golang-jwt/jwt/v5"

	"github.com/crewjam/saml/samlsp"
)

func main() {
	handler := http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
		// A single attribute value:
		email := samlsp.AttributeFromContext(r.Context(), "mail")
		fmt.Println("mail:", email)

		session := samlsp.SessionFromContext(r.Context())

		// All values of an attribute:
		if s, ok := session.(samlsp.SessionWithAttributes); ok {
			fmt.Println("groups:", s.GetAttributes()["eduPersonAffiliation"])
		}

		// The NameID from the assertion's Subject:
		if claims, ok := session.(samlsp.JWTSessionClaims); ok {
			fmt.Println("NameID:", claims.Subject)
		}
	})

	// In a real service, RequireAccount puts the session in the request
	// context. Here we put one there by hand.
	session := samlsp.JWTSessionClaims{
		RegisteredClaims: jwt.RegisteredClaims{Subject: "jdoe@example.com"},
		Attributes: samlsp.Attributes{
			"mail":                 {"jdoe@example.com"},
			"eduPersonAffiliation": {"member", "staff"},
		},
	}
	r := httptest.NewRequest("GET", "/hello", nil)
	r = r.WithContext(samlsp.ContextWithSession(r.Context(), session))
	handler.ServeHTTP(httptest.NewRecorder(), r)

}
Output:
mail: jdoe@example.com
groups: [member staff]
NameID: jdoe@example.com
Example (SessionMaxAge)

This example shows how to change how long a session lasts. It replaces the CookieMaxAge option that was removed from Options.

The session lifetime is set in two places: the MaxAge of the cookie (CookieSessionProvider.MaxAge) and the expiry of the JWT stored in that cookie (JWTSessionCodec.MaxAge). Set both. If only the cookie's MaxAge is raised, the browser keeps the cookie but the token in it is rejected once the JWT expires, after the default one hour.

package main

import (
	"crypto/rand"
	"crypto/rsa"
	"fmt"
	"net/url"
	"time"

	"github.com/crewjam/saml/samlsp"
)

func main() {
	key, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		panic(err)
	}
	rootURL, _ := url.Parse("https://sp.example.com/")

	opts := samlsp.Options{
		URL: *rootURL,
		Key: key,
		// ... and the rest of your options, e.g. Certificate and IDPMetadata
	}

	sessionMaxAge := 12 * time.Hour

	codec := samlsp.DefaultSessionCodec(opts)
	codec.MaxAge = sessionMaxAge

	sessionProvider := samlsp.DefaultSessionProvider(opts)
	sessionProvider.MaxAge = sessionMaxAge
	sessionProvider.Codec = codec

	middleware, err := samlsp.New(opts)
	if err != nil {
		panic(err)
	}
	middleware.Session = sessionProvider

	fmt.Println(middleware.Session.(samlsp.CookieSessionProvider).MaxAge)
}
Output:
12h0m0s

Index

Examples

Constants

View Source
const (
	DefaultFormReplayMaxFormSize = 64 << 10
	DefaultFormReplayMaxEntries  = 1000
	DefaultFormReplayMaxAge      = 5 * time.Minute
)

Defaults of MemoryFormReplayStore.

Variables

View Source
var ErrFormTooLarge = errors.New("saml: form is too large to save for replay after login")

ErrFormTooLarge is returned by MemoryFormReplayStore.SaveForm when the body of a POST request is larger than its MaxFormSize. The middleware passes it to OnError, and does not start the auth flow.

View Source
var ErrNoSession = errors.New("saml: session not present")

ErrNoSession is the error returned when the remote user does not have a session

View Source
var ErrReplayCacheFull = errors.New("samlsp: replay cache is full")

ErrReplayCacheFull is returned by a MemoryReplayCache that holds its maximum number of unexpired assertion IDs. The assertion is refused.

View Source
var ErrSessionCookieTooLarge = errors.New("saml: session cookie too large")

ErrSessionCookieTooLarge is returned (wrapped) by CookieSessionProvider.CreateSession when the encoded session does not fit in a cookie. Browsers silently drop such a cookie, so the user would come back without a session and be sent to the IdP again, in a loop. This usually means the IdP sends more attributes than fit in a cookie; filter them with a custom SessionCodec, or store sessions server side with a custom SessionProvider.

View Source
var MaxMetadataSize int64 = 256 << 20

MaxMetadataSize is the size in bytes of the largest metadata document that FetchMetadata and the other Fetch functions read. A larger response is refused rather than read into memory in full. The default leaves room for federation aggregates, which run to tens of megabytes; lower it when fetching a single IDP's metadata.

Functions

func AttributeFromContext added in v0.4.0

func AttributeFromContext(ctx context.Context, name string) string

AttributeFromContext is a convenience method that returns the named attribute from the session, if available.

func ContextWithSession added in v0.4.0

func ContextWithSession(ctx context.Context, session Session) context.Context

ContextWithSession returns a new context with session associated

func DefaultOnError added in v0.4.0

func DefaultOnError(w http.ResponseWriter, _ *http.Request, err error)

DefaultOnError is the default ErrorFunction implementation. It prints a message via the standard log package and returns a simple text "Forbidden" message to the user. If err is, or wraps, a *saml.InvalidResponseError, its private details are logged.

func DefaultServiceProvider added in v0.4.0

func DefaultServiceProvider(opts Options) saml.ServiceProvider

DefaultServiceProvider returns the default saml.ServiceProvider for the provided options.

func FetchMetadata added in v0.4.0

func FetchMetadata(ctx context.Context, httpClient *http.Client, metadataURL url.URL) (*saml.EntityDescriptor, error)

FetchMetadata returns metadata from an IDP metadata URL.

The metadata names the certificates the service provider trusts to sign assertions, so whoever controls the response controls who can log in. It is not authenticated beyond what httpClient does: use an https URL, and prefer FetchSignedMetadata, or metadata kept with the application.

func FetchMetadataByEntityID added in v0.6.0

func FetchMetadataByEntityID(ctx context.Context, httpClient *http.Client, metadataURL url.URL, entityID string) (*saml.EntityDescriptor, error)

FetchMetadataByEntityID fetches metadata from metadataURL and returns the entity whose entityID is entityID. Use it to select an IDP from aggregate metadata, such as a federation's metadata feed. See ParseMetadataByEntityID.

func FetchSignedMetadata added in v0.6.1

func FetchSignedMetadata(ctx context.Context, httpClient *http.Client, metadataURL url.URL, certs []*x509.Certificate) (*saml.EntityDescriptor, error)

FetchSignedMetadata fetches metadata from metadataURL and parses it with ParseSignedMetadata: its root element must carry a valid signature made with one of certs.

func FetchSignedMetadataByEntityID added in v0.6.1

func FetchSignedMetadataByEntityID(ctx context.Context, httpClient *http.Client, metadataURL url.URL, entityID string, certs []*x509.Certificate) (*saml.EntityDescriptor, error)

FetchSignedMetadataByEntityID fetches metadata from metadataURL and parses it with ParseSignedMetadataByEntityID.

func ParseMetadata added in v0.4.0

func ParseMetadata(data []byte) (*saml.EntityDescriptor, error)

ParseMetadata parses arbitrary SAML IDP metadata.

Note: this is needed because IDP metadata is sometimes wrapped in an <EntitiesDescriptor>, and sometimes the top level element is an <EntityDescriptor>.

An <EntitiesDescriptor> must hold exactly one entity with an IDPSSODescriptor (nested <EntitiesDescriptor> elements included), which is returned: ParseMetadata cannot tell which of several IDPs the caller means to trust. Use ParseMetadataByEntityID to pick one out of an aggregate.

ParseMetadata does not check a signature on the metadata, so the metadata must come from a source the caller trusts. See ParseSignedMetadata.

func ParseMetadataByEntityID added in v0.6.0

func ParseMetadataByEntityID(data []byte, entityID string) (*saml.EntityDescriptor, error)

ParseMetadataByEntityID parses SAML metadata and returns the EntityDescriptor whose entityID is entityID.

The metadata may be a single <EntityDescriptor> or an <EntitiesDescriptor> aggregate, such as the metadata published by a federation (e.g. eduGAIN or InCommon). Nested <EntitiesDescriptor> elements are searched too. Unlike ParseMetadata, which returns the first entity with an IDPSSODescriptor, this lets the caller pick a specific IDP out of an aggregate.

It returns an error if no entity with that entityID is found.

func ParseSignedMetadata added in v0.6.1

func ParseSignedMetadata(data []byte, certs []*x509.Certificate) (*saml.EntityDescriptor, error)

ParseSignedMetadata is ParseMetadata for metadata whose root element must carry a valid enveloped XML signature made with one of certs, the IDP's (or its federation's) metadata signing certificates, obtained from a source the caller trusts. Only the content the signature covers is parsed. See saml.VerifyMetadataSignature.

func ParseSignedMetadataByEntityID added in v0.6.1

func ParseSignedMetadataByEntityID(data []byte, entityID string, certs []*x509.Certificate) (*saml.EntityDescriptor, error)

ParseSignedMetadataByEntityID is ParseMetadataByEntityID for metadata whose root element must carry a valid enveloped XML signature made with one of certs. See ParseSignedMetadata.

func RequireAttribute

func RequireAttribute(name, value string) func(http.Handler) http.Handler

RequireAttribute returns a middleware function that requires that the SAML attribute `name` be set to `value`. This can be used to require that a remote user be a member of a group. It relies on the Claims assigned to to the context in RequireAccount.

Types

type AssertionHandler added in v0.5.0

type AssertionHandler interface {
	HandleAssertion(assertion *saml.Assertion) error
}

AssertionHandler is an interface implemented by types that can handle assertions and add extra functionality

type Attributes

type Attributes map[string][]string

Attributes is a map of attributes provided in the SAML assertion

func (Attributes) Get

func (a Attributes) Get(key string) string

Get returns the first attribute named `key` or an empty string if no such attributes is present.

type CookieRequestTracker added in v0.4.0

type CookieRequestTracker struct {
	ServiceProvider *saml.ServiceProvider
	NamePrefix      string
	Codec           TrackedRequestCodec
	MaxAge          time.Duration
	RelayStateFunc  func(w http.ResponseWriter, r *http.Request) string
	SameSite        http.SameSite

	// Path is the Path attribute of the tracking cookies, which must cover
	// the endpoint the IDP answers at. If empty, it is the path of the ACS
	// URL.
	Path string
}

CookieRequestTracker tracks requests by setting a uniquely named cookie for each request.

The cookie must be sent back by the browser when the IDP POSTs the SAML response to the ACS URL, which is a cross-site request. Browsers treat a cookie without a SameSite attribute as SameSite=Lax and do not send it on a cross-site POST, so when SameSite is unset (zero or http.SameSiteDefaultMode) and the ACS URL uses https, the cookie is issued with SameSite=None (and Secure). Set SameSite explicitly to override this.

func DefaultLogoutRequestTracker added in v0.6.0

func DefaultLogoutRequestTracker(opts Options, serviceProvider *saml.ServiceProvider) CookieRequestTracker

DefaultLogoutRequestTracker returns a new RequestTracker for the LogoutRequests of SP initiated single logout: a CookieRequestTracker whose cookies are sent to the SLO URL. Its cookie names do not share the prefix of DefaultRequestTracker, so a logout request ID is never accepted as the ID of an authentication request, nor the other way around.

func DefaultRequestTracker added in v0.4.0

func DefaultRequestTracker(opts Options, serviceProvider *saml.ServiceProvider) CookieRequestTracker

DefaultRequestTracker returns a new RequestTracker for the provided options, a CookieRequestTracker which uses cookies to track pending requests.

func (CookieRequestTracker) GetTrackedRequest added in v0.4.0

func (t CookieRequestTracker) GetTrackedRequest(r *http.Request, index string) (*TrackedRequest, error)

GetTrackedRequest returns a pending tracked request.

func (CookieRequestTracker) GetTrackedRequests added in v0.4.0

func (t CookieRequestTracker) GetTrackedRequests(r *http.Request) []TrackedRequest

GetTrackedRequests returns all the pending tracked requests

func (CookieRequestTracker) StopTrackingRequest added in v0.4.0

func (t CookieRequestTracker) StopTrackingRequest(w http.ResponseWriter, r *http.Request, index string) error

StopTrackingRequest stops tracking the SAML request given by index, which is a string previously returned from TrackRequest

func (CookieRequestTracker) TrackRequest added in v0.4.0

func (t CookieRequestTracker) TrackRequest(w http.ResponseWriter, r *http.Request, samlRequestID string) (string, error)

TrackRequest starts tracking the SAML request with the given ID. It returns an `index` that should be used as the RelayState in the SAMl request flow.

type CookieSessionProvider added in v0.4.0

type CookieSessionProvider struct {
	Name     string
	Domain   string
	HTTPOnly bool
	Secure   bool
	SameSite http.SameSite

	// MaxAge is the lifetime of the session cookie. When Codec is a
	// JWTSessionCodec, set its MaxAge to the same value: the token expires on
	// its own after that, whatever the cookie's lifetime. See the
	// Example (SessionMaxAge).
	MaxAge time.Duration
	Path   string
	Codec  SessionCodec
	// contains filtered or unexported fields
}

CookieSessionProvider is an implementation of SessionProvider that stores session tokens in an HTTP cookie.

func DefaultSessionProvider added in v0.4.0

func DefaultSessionProvider(opts Options) CookieSessionProvider

DefaultSessionProvider returns the default SessionProvider for the provided options, a CookieSessionProvider configured to store sessions in a cookie.

func (CookieSessionProvider) CreateSession added in v0.4.0

func (c CookieSessionProvider) CreateSession(w http.ResponseWriter, r *http.Request, assertion *saml.Assertion) error

CreateSession is called when we have received a valid SAML assertion and should create a new session and modify the http response accordingly, e.g. by setting a cookie.

func (CookieSessionProvider) DeleteSession added in v0.4.0

func (c CookieSessionProvider) DeleteSession(w http.ResponseWriter, r *http.Request) error

DeleteSession is called to modify the response such that it removed the current session, e.g. by deleting a cookie.

func (CookieSessionProvider) GetSession added in v0.4.0

func (c CookieSessionProvider) GetSession(r *http.Request) (Session, error)

GetSession returns the current Session associated with the request, or an error matching ErrNoSession (as determined by errors.Is) if there is no valid session. When the cookie is present but cannot be decoded, the returned error also wraps the error from Codec.Decode, so callers can see why the session was rejected.

type ErrorFunction added in v0.4.0

type ErrorFunction func(w http.ResponseWriter, r *http.Request, err error)

ErrorFunction is a callback that is invoked to return an error to the web user.

type FormReplayStore added in v0.6.1

type FormReplayStore interface {
	// SaveForm is called by HandleStartAuthFlow for a same-origin POST
	// request r that has no session. index is the RelayState of the auth
	// flow, as returned by the RequestTracker. SaveForm may save the form of
	// r under index, and reports whether it did.
	//
	// If it returns false and a nil error, the form is not replayed, and the
	// user is redirected to the URI of r with a GET request after login, as
	// when Middleware.FormReplayStore is nil. A non-nil error is passed to
	// OnError, and the auth flow does not start.
	SaveForm(r *http.Request, index string) (bool, error)

	// TakeForm returns and deletes the form saved under index. It reports
	// false if there is no such form, or if it has expired.
	TakeForm(r *http.Request, index string) (form *SavedForm, ok bool, err error)
}

FormReplayStore saves the form of a POST request that starts the SAML auth flow, so that the middleware can post it again once the user has logged in. See Middleware.FormReplayStore.

A FormReplayStore must keep the forms on the server, or encrypt them: they can hold passwords, tokens or personal data.

type JWTSessionClaims added in v0.4.0

type JWTSessionClaims struct {
	jwt.RegisteredClaims
	Attributes  Attributes `json:"attr"`
	SAMLSession bool       `json:"saml-session"`
}

JWTSessionClaims represents the JWT claims in the encoded session

func (JWTSessionClaims) GetAttributes added in v0.4.0

func (c JWTSessionClaims) GetAttributes() Attributes

GetAttributes implements SessionWithAttributes. It returns the SAMl attributes.

func (JWTSessionClaims) GetNameID added in v0.6.0

func (c JWTSessionClaims) GetNameID() string

GetNameID implements SessionWithNameID. It returns the NameID of the assertion the session was made from, which JWTSessionCodec stores as the JWT subject.

type JWTSessionCodec added in v0.4.0

type JWTSessionCodec struct {
	SigningMethod jwt.SigningMethod
	Audience      string
	Issuer        string

	// MaxAge is how long an issued session token is valid. It should match
	// the MaxAge of the CookieSessionProvider that stores the token.
	MaxAge time.Duration
	Key    crypto.Signer
}

JWTSessionCodec implements SessionCoded to encode and decode Sessions from the corresponding JWT.

func DefaultSessionCodec added in v0.4.0

func DefaultSessionCodec(opts Options) JWTSessionCodec

DefaultSessionCodec returns the default SessionCodec for the provided options, a JWTSessionCodec configured to issue signed tokens.

func (JWTSessionCodec) Decode added in v0.4.0

func (c JWTSessionCodec) Decode(signed string) (Session, error)

Decode parses the serialized session that may have been returned by Encode and returns a Session.

func (JWTSessionCodec) Encode added in v0.4.0

func (c JWTSessionCodec) Encode(s Session) (string, error)

Encode returns a serialized version of the Session.

The provided session must be a JWTSessionClaims, otherwise this function will panic.

func (JWTSessionCodec) New added in v0.4.0

func (c JWTSessionCodec) New(assertion *saml.Assertion) (Session, error)

New creates a Session from the SAML assertion.

The returned Session is a JWTSessionClaims.

type JWTTrackedRequestClaims added in v0.4.0

type JWTTrackedRequestClaims struct {
	jwt.RegisteredClaims
	TrackedRequest
	SAMLAuthnRequest bool `json:"saml-authn-request"`
}

JWTTrackedRequestClaims represents the JWT claims for a tracked request.

type JWTTrackedRequestCodec added in v0.4.0

type JWTTrackedRequestCodec struct {
	SigningMethod jwt.SigningMethod
	Audience      string
	Issuer        string
	MaxAge        time.Duration
	Key           crypto.Signer
}

JWTTrackedRequestCodec encodes TrackedRequests as signed JWTs

func DefaultTrackedRequestCodec added in v0.4.0

func DefaultTrackedRequestCodec(opts Options) JWTTrackedRequestCodec

DefaultTrackedRequestCodec returns a new TrackedRequestCodec for the provided options, a JWTTrackedRequestCodec that uses a JWT to encode TrackedRequests.

func (JWTTrackedRequestCodec) Decode added in v0.4.0

func (s JWTTrackedRequestCodec) Decode(signed string) (*TrackedRequest, error)

Decode returns a Tracked request from an encoded string.

func (JWTTrackedRequestCodec) Encode added in v0.4.0

Encode returns an encoded string representing the TrackedRequest.

type MemoryFormReplayStore added in v0.6.1

type MemoryFormReplayStore struct {
	// MaxFormSize is the largest form body, in bytes, that is saved. A larger
	// form makes SaveForm return ErrFormTooLarge. If zero,
	// DefaultFormReplayMaxFormSize is used.
	MaxFormSize int64

	// MaxEntries is the largest number of forms kept at once. When the store
	// is full, forms are not saved, and the user is redirected with a GET
	// request after login. If zero, DefaultFormReplayMaxEntries is used.
	MaxEntries int

	// MaxAge is how long a saved form is kept. If zero,
	// DefaultFormReplayMaxAge is used.
	MaxAge time.Duration

	// Allow, if set, decides which requests have their form saved. It
	// should accept only forms that are safe to post again once the user
	// has logged in. If nil, every application/x-www-form-urlencoded form
	// is saved.
	Allow func(r *http.Request) bool
	// contains filtered or unexported fields
}

MemoryFormReplayStore is a FormReplayStore that keeps forms in memory. It saves only application/x-www-form-urlencoded forms: a multipart form, which may carry files, is not replayed.

The forms are kept in the memory of one process, so an application that runs more than one instance behind a load balancer needs sticky sessions, or a FormReplayStore of its own backed by shared storage.

The zero value is ready to use. A MemoryFormReplayStore must not be copied after first use.

func (*MemoryFormReplayStore) SaveForm added in v0.6.1

func (s *MemoryFormReplayStore) SaveForm(r *http.Request, index string) (bool, error)

SaveForm implements FormReplayStore.

func (*MemoryFormReplayStore) TakeForm added in v0.6.1

func (s *MemoryFormReplayStore) TakeForm(_ *http.Request, index string) (*SavedForm, bool, error)

TakeForm implements FormReplayStore.

type MemoryReplayCache added in v0.6.1

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

MemoryReplayCache is a saml.AssertionReplayCache that keeps the IDs of accepted assertions in memory, each until the expiry it was recorded with. It is safe for concurrent use.

It only protects a single process: an assertion accepted by one server is not known to another server, nor to this one after a restart. Deployments with more than one server must use a shared store instead.

It holds at most maxEntries IDs. An ID is dropped once its expiry has passed, which is at most saml.MaxIssueDelay plus saml.MaxClockSkew after the assertion was issued, so maxEntries should exceed the number of logins expected in that period. When the cache is full of unexpired IDs, Consume refuses new assertions with ErrReplayCacheFull rather than dropping an unexpired ID, since dropping one would let that assertion be replayed. A full cache therefore blocks logins until its oldest IDs expire.

Expiry is judged by saml.TimeNow, so it is meant for a ServiceProvider that uses the default clock.

func NewMemoryReplayCache added in v0.6.1

func NewMemoryReplayCache(maxEntries int) *MemoryReplayCache

NewMemoryReplayCache returns a MemoryReplayCache that holds at most maxEntries unexpired assertion IDs. It panics if maxEntries is not positive.

func (*MemoryReplayCache) Consume added in v0.6.1

func (c *MemoryReplayCache) Consume(assertionID string, expiresAt time.Time) error

Consume implements saml.AssertionReplayCache.

type Middleware

type Middleware struct {
	ServiceProvider  saml.ServiceProvider
	OnError          func(w http.ResponseWriter, r *http.Request, err error)
	Binding          string // saml.HTTPRedirectBinding, saml.HTTPPostBinding or saml.HTTPPostSimpleSignBinding
	ResponseBinding  string // saml.HTTPPostBinding, saml.HTTPArtifactBinding or saml.HTTPPostSimpleSignBinding
	RequestTracker   RequestTracker
	Session          SessionProvider
	AssertionHandler AssertionHandler

	// LogoutRequestTracker tracks the LogoutRequests sent by
	// HandleStartLogout, so that ServeSLO accepts only a LogoutResponse to
	// one of them. It must not share pending requests with RequestTracker.
	// SP initiated single logout fails if it is nil.
	LogoutRequestTracker RequestTracker

	// ScriptNonce, if set, is called when the middleware serves the
	// auto-submitting HTML form of the HTTP-POST binding. A non-empty result
	// is set as the nonce attribute of the form's <script> element, for
	// applications whose own Content-Security-Policy allows scripts by nonce.
	ScriptNonce func(r *http.Request) string

	// FormReplayStore, if set, lets a POST request that starts the auth flow
	// be posted again once the user has logged in. If it is nil, the
	// default, the user is redirected to the URI of the request with a GET
	// request, and the form is lost.
	//
	// The form is saved only if the browser says the request comes from a
	// page on the same origin (by the Sec-Fetch-Site or Origin header), and
	// only if the FormReplayStore accepts it. After login it is posted back
	// by an auto-submitting form, which carries the new session cookie.
	// Enable this only for forms that are safe to submit again, and keep
	// validating them, CSRF tokens included, as usual.
	//
	// Forms are saved under the RelayState returned by the RequestTracker,
	// which must be unique to each auth flow: a RelayStateFunc that returns
	// a fixed value must not be used with FormReplayStore.
	FormReplayStore FormReplayStore

	// LogoutBinding is the binding preferred for sending logout messages to
	// the IDP (LogoutRequests from HandleStartLogout, and LogoutResponses to
	// IDP initiated logout): saml.HTTPRedirectBinding,
	// saml.HTTPPostBinding or saml.HTTPPostSimpleSignBinding. It is used
	// when the IDP metadata has a SingleLogoutService endpoint for it.
	// Otherwise, and when it is empty, HTTP-Redirect is used if the IDP
	// supports it, HTTP-POST otherwise. The HTTP-POST-SimpleSign binding
	// signs messages with ServiceProvider.Key and SignatureMethod, which
	// must be set.
	LogoutBinding string
}

Middleware implements middleware than allows a web application to support SAML.

It implements http.Handler so that it can provide the metadata and ACS endpoints, typically /saml/metadata and /saml/acs, respectively.

It also provides middleware RequireAccount which redirects users to the auth process if they do not have session credentials.

When redirecting the user through the SAML auth flow, the middleware assigns a temporary cookie with a random name beginning with "saml_". The value of the cookie is a signed JSON Web Token containing the original URL requested and the SAML request ID. The random part of the name corresponds to the RelayState parameter passed through the SAML flow.

When validating the SAML response, the RelayState is used to look up the correct cookie, validate that the SAML request ID, and redirect the user back to their original URL.

Sessions are established by issuing a JSON Web Token (JWT) as a session cookie once the SAML flow has succeeded. The JWT token contains the authenticated attributes from the SAML assertion.

When the middleware receives a request with a valid session JWT it extracts the SAML attributes and modifies the http.Request object adding a Context object to the request context that contains attributes from the initial SAML assertion.

When issuing JSON Web Tokens, a signing key is required. Because the SAML service provider already has a private key, we borrow that key to sign the JWTs as well.

func New

func New(opts Options) (*Middleware, error)

New creates a new Middleware with the default providers for the given options.

You can customize the behavior of the middleware in more detail by replacing and/or changing Session, RequestTracker, LogoutRequestTracker and ServiceProvider in the returned Middleware.

func (*Middleware) CreateSessionFromAssertion added in v0.4.0

func (m *Middleware) CreateSessionFromAssertion(w http.ResponseWriter, r *http.Request, assertion *saml.Assertion, redirectURI string)

CreateSessionFromAssertion is invoked by ServeHTTP when we have a new, valid SAML assertion.

func (*Middleware) HandleStartAuthFlow added in v0.4.0

func (m *Middleware) HandleStartAuthFlow(w http.ResponseWriter, r *http.Request)

HandleStartAuthFlow is called to start the SAML authentication process.

func (*Middleware) HandleStartLogout added in v0.6.0

func (m *Middleware) HandleStartLogout(w http.ResponseWriter, r *http.Request)

HandleStartLogout starts SP initiated single logout. It deletes the local session and sends the browser to the IDP with a LogoutRequest for the session's NameID (and SessionIndex, if known), using LogoutBinding if it is set and the IDP supports it, otherwise the HTTP-Redirect binding if the IDP supports it and the HTTP-POST binding otherwise. The request is tracked with LogoutRequestTracker, and its index is the RelayState. The IDP answers with a LogoutResponse to ServiceProvider.SloURL, which ServeHTTP handles (see ServeSLO).

If the request has no session, or the IDP metadata lists no SingleLogoutService, only the local session is ended and the browser is redirected to "/".

To use it, route a path of your application to it, for example:

http.HandleFunc("/logout", samlMiddleware.HandleStartLogout)

func (*Middleware) RequireAccount

func (m *Middleware) RequireAccount(handler http.Handler) http.Handler

RequireAccount is HTTP middleware that requires that each request be associated with a valid session. If the request is not associated with a valid session, then rather than serve the request, the middleware redirects the user to start the SAML auth flow.

If the SessionProvider returns an error that matches ErrNoSession (as determined by errors.Is), the auth flow is started. Any other error, or a nil session, is passed to OnError and the wrapped handler is not called, even if the SessionProvider also returned a non-nil session.

func (*Middleware) ServeACS added in v0.4.6

func (m *Middleware) ServeACS(w http.ResponseWriter, r *http.Request)

ServeACS handles requests for the SAML ACS endpoint.

func (*Middleware) ServeHTTP

func (m *Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler and serves the SAML-specific HTTP endpoints on the URIs specified by m.ServiceProvider.MetadataURL, m.ServiceProvider.AcsURL and m.ServiceProvider.SloURL.

func (*Middleware) ServeMetadata added in v0.4.6

func (m *Middleware) ServeMetadata(w http.ResponseWriter, _ *http.Request)

ServeMetadata handles requests for the SAML metadata endpoint. If ServiceProvider.SignMetadata is set, the metadata is signed.

func (*Middleware) ServeSLO added in v0.6.0

func (m *Middleware) ServeSLO(w http.ResponseWriter, r *http.Request)

ServeSLO handles requests for the SAML SingleLogoutService endpoint, ServiceProvider.SloURL, using the HTTP-Redirect, HTTP-POST or HTTP-POST-SimpleSign binding.

A LogoutResponse is the IDP's answer to a LogoutRequest sent by HandleStartLogout. It is accepted only if its InResponseTo is the ID of a LogoutRequest pending in LogoutRequestTracker. Once it is validated, the request stops being tracked, the session (if any is left) is deleted and the browser is redirected to "/".

A LogoutRequest is IDP initiated single logout. Once it is validated, the session of the requesting browser is deleted and the browser is sent back to the IDP with a LogoutResponse. A SessionProvider that keeps sessions on the server, rather than in a cookie, should also end the sessions of the request's NameID; such applications can handle SloURL themselves with ServiceProvider.ValidateLogoutRequest.

Invalid messages are passed to OnError.

type NopAssertionHandler added in v0.5.0

type NopAssertionHandler struct{}

NopAssertionHandler is an implementation of AssertionHandler that does nothing.

func DefaultAssertionHandler added in v0.5.0

func DefaultAssertionHandler(_ Options) NopAssertionHandler

DefaultAssertionHandler returns the default AssertionHandler for the provided options, a NopAssertionHandler configured to do nothing.

func (NopAssertionHandler) HandleAssertion added in v0.5.0

func (as NopAssertionHandler) HandleAssertion(_ *saml.Assertion) error

HandleAssertion is called and passed a SAML assertion. This implementation does nothing.

type Options

type Options struct {
	EntityID              string
	URL                   url.URL
	Key                   crypto.Signer
	Certificate           *x509.Certificate
	Intermediates         []*x509.Certificate
	HTTPClient            *http.Client
	AllowIDPInitiated     bool
	DefaultRedirectURI    string
	IDPMetadata           *saml.EntityDescriptor
	SignRequest           bool
	UseArtifactResponse   bool
	ForceAuthn            bool // TODO(ross): this should be *bool
	RequestedAuthnContext *saml.RequestedAuthnContext
	// CookieSameSite sets the SameSite attribute of the session and request
	// tracking cookies. When it is unset and URL uses https, the request
	// tracking cookie is issued with SameSite=None, because browsers do not
	// send a SameSite=Lax cookie with the IDP's cross-site POST to the ACS URL.
	// See CookieRequestTracker.
	CookieSameSite http.SameSite
	CookieName     string
	RelayStateFunc func(w http.ResponseWriter, r *http.Request) string
	LogoutBindings []string

	// CookieDomain, if set, is the Domain attribute of the session cookie,
	// which makes the browser also send the cookie to subdomains of that
	// domain. If empty, the session cookie is a host-only cookie, sent only to
	// the host of URL.
	//
	// Earlier versions always scoped the session cookie to the host of URL.
	// To keep sharing the session with subdomains, set CookieDomain to that
	// host (or to a parent domain).
	CookieDomain string

	// EncryptionKey and EncryptionCertificate, if set, are used to decrypt
	// encrypted assertions and are advertised in the metadata for encryption,
	// instead of Key and Certificate. See saml.ServiceProvider.
	EncryptionKey         *rsa.PrivateKey
	EncryptionCertificate *x509.Certificate

	// DecryptionKeys are further keys that decrypt encrypted assertions, for
	// key rotation. See saml.ServiceProvider.
	DecryptionKeys []*rsa.PrivateKey

	// AssertionConsumerServiceBindings specify the bindings advertised for the
	// AssertionConsumerService endpoint in the SP metadata. If empty, both
	// HTTP-POST and HTTP-Artifact bindings are advertised. If set, it must
	// include the binding requested for responses (HTTP-Artifact when
	// UseArtifactResponse is true, HTTP-POST otherwise), or New returns an
	// error.
	AssertionConsumerServiceBindings []string

	// Binding is the binding used to send authentication requests to the
	// IDP: saml.HTTPRedirectBinding, saml.HTTPPostBinding or
	// saml.HTTPPostSimpleSignBinding. If empty, HTTP-Redirect is used when
	// the IDP metadata has an endpoint for it, HTTP-POST otherwise. The
	// HTTP-POST-SimpleSign binding signs requests with Key, so it requires
	// SignRequest. See Middleware.Binding.
	Binding string

	// UseSimpleSignResponse asks the IDP to send responses with the
	// HTTP-POST-SimpleSign binding instead of HTTP-POST. It cannot be
	// combined with UseArtifactResponse. When AssertionConsumerServiceBindings
	// is empty, the metadata then advertises HTTP-POST-SimpleSign and
	// HTTP-POST for the ACS. The ACS accepts both bindings either way.
	UseSimpleSignResponse bool

	// LogoutBinding is the binding preferred for sending single logout
	// messages to the IDP: saml.HTTPRedirectBinding, saml.HTTPPostBinding
	// or saml.HTTPPostSimpleSignBinding. If empty, or if the IDP metadata
	// has no SingleLogoutService endpoint for it, HTTP-Redirect is used when
	// the IDP supports it, HTTP-POST otherwise. The HTTP-POST-SimpleSign
	// binding requires SignRequest. See Middleware.LogoutBinding. (The
	// bindings this SP advertises for receiving logout messages are set by
	// LogoutBindings.)
	LogoutBinding string

	// AcsIndex, if set, makes authentication requests name the
	// AssertionConsumerService endpoint by its index in the SP metadata
	// instead of by URL and binding. See saml.ServiceProvider.AcsIndex.
	AcsIndex *int

	// IgnoreCertificateExpiry, if true, accepts signatures made with an IDP
	// signing certificate outside its validity period. See
	// saml.ServiceProvider.IgnoreCertificateExpiry.
	IgnoreCertificateExpiry bool

	// SignMetadata, if true, makes the metadata endpoint serve metadata
	// signed with Key. See saml.ServiceProvider.SignMetadata.
	SignMetadata bool

	// MetadataPath, AcsPath and SloPath set the paths of the SAML metadata,
	// AssertionConsumerService and SingleLogoutService endpoints. Each is
	// resolved as a URL reference against URL, so a relative path (such as
	// the defaults "saml/metadata", "saml/acs" and "saml/slo") is appended to
	// the path of URL, and an absolute path (beginning with "/") replaces it.
	// Empty values use the defaults. When EntityID is empty the metadata URL is
	// used as the entity ID, so changing MetadataPath changes it too.
	MetadataPath string
	AcsPath      string
	SloPath      string

	// SessionKey, if set, signs and verifies the session JWTs and the
	// tracked-request JWTs issued by the default SessionCodec and
	// TrackedRequestCodec, instead of Key. Use it to keep the key that
	// protects this SP's own cookies separate from the SAML key, for example
	// so that the SAML key can live in an HSM or be rotated with the IdP
	// without invalidating sessions, or so that a leaked session key does not
	// let anyone sign SAML requests. The JWT signing method follows the type
	// of the key: RS256 for RSA, ES256/ES384/ES512 for ECDSA (by curve) and
	// EdDSA for Ed25519. If nil, Key is used, as before.
	//
	// Changing the session key invalidates existing sessions and pending
	// requests.
	SessionKey crypto.Signer

	// ReplayCache, if set, records the ID of each accepted assertion and
	// refuses an assertion it has already recorded. See
	// saml.ServiceProvider.ReplayCache. NewMemoryReplayCache returns one for
	// a single process. If nil, assertions are not checked for replay.
	ReplayCache saml.AssertionReplayCache
}

Options represents the parameters for creating a new middleware

type RequestTracker added in v0.4.0

type RequestTracker interface {
	// TrackRequest starts tracking the SAML request with the given ID. It returns an
	// `index` that should be used as the RelayState in the SAMl request flow.
	TrackRequest(w http.ResponseWriter, r *http.Request, samlRequestID string) (index string, err error)

	// StopTrackingRequest stops tracking the SAML request given by index, which is a string
	// previously returned from TrackRequest
	StopTrackingRequest(w http.ResponseWriter, r *http.Request, index string) error

	// GetTrackedRequests returns all the pending tracked requests
	GetTrackedRequests(r *http.Request) []TrackedRequest

	// GetTrackedRequest returns a pending tracked request.
	GetTrackedRequest(r *http.Request, index string) (*TrackedRequest, error)
}

RequestTracker tracks pending authentication requests.

There are two main reasons for this:

  1. When the middleware initiates an authentication request it must track the original URL in order to redirect the user to the right place after the authentication completes.

  2. After the authentication completes, we want to ensure that the user presenting the assertion is actually the one the request it, to mitigate request forgeries.

type SavedForm added in v0.6.1

type SavedForm struct {
	// URI is the URI of the request the form was posted to, as r.URL.String().
	URI string

	// Form holds the fields of the form.
	Form url.Values
}

SavedForm is a form saved by a FormReplayStore.

type Session added in v0.4.0

type Session interface{}

Session is an interface implemented to contain a session.

func SessionFromContext added in v0.4.0

func SessionFromContext(ctx context.Context) Session

SessionFromContext returns the session associated with ctx, or nil if no session are associated

type SessionCodec added in v0.4.0

type SessionCodec interface {
	// New creates a Session from the SAML assertion.
	New(assertion *saml.Assertion) (Session, error)

	// Encode returns a serialized version of the Session.
	//
	// Note: When implementing this function, it is reasonable to expect that
	// Session is of the exact type returned by New(), and panic if it is not.
	Encode(s Session) (string, error)

	// Decode parses the serialized session that may have been returned by Encode
	// and returns a Session.
	Decode(string) (Session, error)
}

SessionCodec is an interface to convert SAML assertions to a Session. The default implementation uses JWTs, JWTSessionCodec.

type SessionProvider added in v0.4.0

type SessionProvider interface {
	// CreateSession is called when we have received a valid SAML assertion and
	// should create a new session and modify the http response accordingly, e.g. by
	// setting a cookie.
	CreateSession(w http.ResponseWriter, r *http.Request, assertion *saml.Assertion) error

	// DeleteSession is called to modify the response such that it removed the current
	// session, e.g. by deleting a cookie.
	DeleteSession(w http.ResponseWriter, r *http.Request) error

	// GetSession returns the current Session associated with the request, or
	// an error matching ErrNoSession (as determined by errors.Is) if there is
	// no valid session. Such an error may wrap the underlying cause.
	GetSession(r *http.Request) (Session, error)
}

SessionProvider is an interface implemented by types that can track the active session of a user. The default implementation is CookieSessionProvider

type SessionWithAttributes added in v0.4.0

type SessionWithAttributes interface {
	Session
	GetAttributes() Attributes
}

SessionWithAttributes is a session that can expose the attributes provided by the SAML identity provider.

type SessionWithNameID added in v0.6.0

type SessionWithNameID interface {
	Session
	GetNameID() string
}

SessionWithNameID is a session that knows the SAML NameID of the user it belongs to. HandleStartLogout needs it to tell the IDP whose session to end.

type TrackedRequest added in v0.4.0

type TrackedRequest struct {
	Index         string `json:"-"`
	SAMLRequestID string `json:"id"`
	URI           string `json:"uri"`
}

TrackedRequest holds the data we store for each pending request.

type TrackedRequestCodec added in v0.4.0

type TrackedRequestCodec interface {
	// Encode returns an encoded string representing the TrackedRequest.
	Encode(value TrackedRequest) (string, error)

	// Decode returns a Tracked request from an encoded string.
	Decode(signed string) (*TrackedRequest, error)
}

TrackedRequestCodec handles encoding and decoding of a TrackedRequest.

Jump to

Keyboard shortcuts

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