samlsp

package
v0.6.2 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: 35 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.

View Source
const DefaultMaxSessionRevocations = 100000

DefaultMaxSessionRevocations is the number of records the MemorySessionRevocationStore of DefaultSessionProvider holds.

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 ErrSessionEnded = errors.New("samlsp: the IdP session has already ended")

ErrSessionEnded is returned when a session would be created from an assertion whose AuthnStatement SessionNotOnOrAfter has already passed.

View Source
var ErrSessionNameIDUnknown = errors.New("saml: the session does not record the user's full NameID; the user must log in again")

ErrSessionNameIDUnknown is returned by Middleware.QueryAttributes when the session does not record the full NameID of its user: a session issued before JWTSessionCodec recorded the NameID's Format and qualifiers, or one from a SessionProvider or SessionCodec that does not implement SessionWithSAMLNameID. The user must log in again to get a session that does.

View Source
var ErrSessionRevocationStoreFull = errors.New("samlsp: session revocation store is full")

ErrSessionRevocationStoreFull is returned by a MemorySessionRevocationStore that holds its maximum number of unexpired records. The sessions are not revoked, and back-channel logout answers the IdP that it failed.

View Source
var ErrSessionRevoked = errors.New("saml: the session has been revoked")

ErrSessionRevoked is wrapped, together with ErrNoSession, in the error CookieSessionProvider.GetSession returns for a session that has been ended by back-channel single logout.

View Source
var ErrSessionTerminationUnsupported = errors.New("saml: the session provider cannot end sessions on the server")

ErrSessionTerminationUnsupported is returned by CookieSessionProvider.TerminateSessions when the provider has no Revocations store, so it cannot end a session without the browser.

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.

When the entity is taken from an <EntitiesDescriptor>, the validUntil and cacheDuration of the enclosing <EntitiesDescriptor> elements are carried down to it, since the caching policy of a parent element takes precedence (saml-metadata-2.0-os §4.3.1): the returned ValidUntil is the earliest validUntil of the entity and of the aggregates that enclose it, and CacheDuration the shortest cacheDuration, among those that are set. ParseMetadataByEntityID and the signed and Fetch variants do the same. See saml.ServiceProvider.RejectExpiredIDPMetadata to refuse to rely on metadata whose validUntil has passed.

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.

Like ParseMetadata, it carries the validUntil and cacheDuration of the enclosing <EntitiesDescriptor> elements down to the returned entity.

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

	// Revocations, if set, records sessions ended by back-channel single
	// logout (see TerminateSessions), and GetSession refuses those sessions
	// as if there were none. The sessions must implement RevocableSession,
	// and Codec must say so by implementing RevocableSessionCodec, as
	// JWTSessionCodec does; the signature of the session token keeps a
	// client from changing what identifies its session. If nil, or if Codec
	// does not implement RevocableSessionCodec, sessions cannot be ended
	// without the browser, and TerminateSessions returns
	// ErrSessionTerminationUnsupported. DefaultSessionProvider sets it.
	Revocations SessionRevocationStore
	// 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. Its Revocations store is opts.SessionRevocations or, if that is nil, a new MemorySessionRevocationStore.

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. A session revoked in Revocations is refused with an error matching both ErrNoSession and ErrSessionRevoked; if Revocations cannot be read, the error does not match ErrNoSession, so the request fails rather than start a new login.

func (CookieSessionProvider) TerminateSessions added in v0.6.2

func (c CookieSessionProvider) TerminateSessions(ctx context.Context, req *saml.LogoutRequest) error

TerminateSessions implements SessionTerminator. It records the sessions that req names in Revocations, where GetSession finds them: every session of req's NameID issued up to now if req has no SessionIndex, and otherwise those with one of its SessionIndexes, as well as those with no SessionIndex at all, which cannot be told apart from them. Sessions issued later, such as after the user logs in again, are not affected. The records are kept until such sessions have expired, the longer of MaxAge and, if Codec is a JWTSessionCodec, its MaxAge, from now.

It returns ErrSessionTerminationUnsupported if Revocations is nil or Codec does not declare, by implementing RevocableSessionCodec, that its sessions can be revoked, and an error matching saml.ErrUnsupported if req identifies the user with a BaseID rather than a NameID.

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"`

	// NameIDFormat, NameIDNameQualifier and NameIDSPNameQualifier are the
	// Format, NameQualifier and SPNameQualifier of the NameID of the
	// assertion the session was made from; its value is the JWT subject.
	// Together they let GetSAMLNameID rebuild that NameID, for example to
	// query the IdP's attribute authority (see Middleware.QueryAttributes).
	// Empty ones are omitted from the JWT. Sessions issued before these
	// claims existed have none of them.
	NameIDFormat          string `json:"saml-nameid-format,omitempty"`
	NameIDNameQualifier   string `json:"saml-nameid-nq,omitempty"`
	NameIDSPNameQualifier string `json:"saml-nameid-spnq,omitempty"`
}

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.

func (JWTSessionClaims) GetSAMLNameID added in v0.6.2

func (c JWTSessionClaims) GetSAMLNameID() (saml.NameID, bool)

GetSAMLNameID implements SessionWithSAMLNameID. It returns the NameID of the assertion the session was made from, with its Format and qualifiers. It returns false if the session does not record the NameID's Format, because it was issued before JWTSessionCodec recorded it, or has no subject.

func (JWTSessionClaims) GetSessionIssuedAt added in v0.6.2

func (c JWTSessionClaims) GetSessionIssuedAt() time.Time

GetSessionIssuedAt implements RevocableSession. It returns the time of the JWT "iat" claim, which has a precision of one second, or the zero time if the token has none.

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

	// KeyAttributesByName, if true, keys the session's Attributes by each
	// SAML attribute's Name. By default they are keyed by FriendlyName, or
	// Name when FriendlyName is empty. saml-core §2.7.3.1 says FriendlyName
	// "MUST NOT be used as a basis for formally identifying SAML
	// attributes": two attributes with different Names but the same
	// FriendlyName are merged under one key, and a FriendlyName can equal
	// another attribute's Name, so an attribute can stand in for another.
	// Set this when attribute values are used for authorization.
	KeyAttributesByName bool
}

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.

func (JWTSessionCodec) RevocableSessions added in v0.6.2

func (JWTSessionCodec) RevocableSessions() bool

RevocableSessions implements RevocableSessionCodec: the JWTSessionClaims it decodes are RevocableSessions, and the JWT signature covers what identifies them.

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 MemorySessionRevocationStore added in v0.6.2

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

MemorySessionRevocationStore is a SessionRevocationStore that keeps its records in memory. It is safe for concurrent use.

It only serves a single process: a session revoked by one server is still accepted by another, and by this one after a restart. Deployments with more than one server must use a shared store instead.

It holds at most maxEntries records. A record is dropped once it has expired, which is when every session it revokes has expired. A logout adds one record, or one per SessionIndex. When the store is full of unexpired records, Revoke refuses new ones with ErrSessionRevocationStoreFull rather than drop an unexpired one, which would let a revoked session be used again.

Expiry is judged by saml.TimeNow.

func NewMemorySessionRevocationStore added in v0.6.2

func NewMemorySessionRevocationStore(maxEntries int) *MemorySessionRevocationStore

NewMemorySessionRevocationStore returns a MemorySessionRevocationStore that holds at most maxEntries unexpired records. It panics if maxEntries is not positive.

func (*MemorySessionRevocationStore) Revoke added in v0.6.2

func (s *MemorySessionRevocationStore) Revoke(_ context.Context, key string, revokedAt, expiresAt time.Time) error

Revoke implements SessionRevocationStore.

func (*MemorySessionRevocationStore) RevokedAt added in v0.6.2

RevokedAt implements SessionRevocationStore.

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.
	//
	// saml.SOAPBinding makes HandleStartLogout send its LogoutRequest from
	// the server, signed with ServiceProvider.Key, when the IDP metadata has
	// a SOAP SingleLogoutService endpoint (see HandleStartLogout). The
	// LogoutResponses to IDP initiated logout are then sent with the
	// default front-channel binding.
	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 its SessionIndexes, 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 LogoutBinding is saml.SOAPBinding, the IDP metadata lists a SOAP SingleLogoutService and the session knows the full NameID of its user (see SessionWithSAMLNameID), the LogoutRequest is instead sent to the IDP from the server, with ServiceProvider.SendSOAPLogoutRequest and the request's context (back-channel single logout, saml-profiles §4.4). The local session is then deleted and the browser redirected to "/", as after a LogoutResponse. If the IDP cannot be reached or does not answer Success, the error is passed to OnError (whose response is discarded), the local session is still deleted, and the browser is sent to the IDP with a LogoutRequest over a front-channel binding, if the IDP supports one, so that the IDP can still end its session with the browser's help; otherwise it is redirected to "/".

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) QueryAttributes added in v0.6.2

func (m *Middleware) QueryAttributes(r *http.Request, attributes ...saml.Attribute) (*saml.AttributeQueryResult, error)

QueryAttributes asks the IdP's attribute authority for attributes of the user of the request's session, with ServiceProvider.QueryAttributes, and returns what it returns. The query is made with the request's context.

The user is named by the NameID the session was made from, with the Format and qualifiers the IdP issued it with, which the session must record (see SessionWithSAMLNameID). The session is the one RequireAccount put in the request's context or, if there is none, the one Session returns for the request.

It returns an error matching ErrNoSession if the request has no session, and one matching ErrSessionNameIDUnknown if the session does not record the full NameID, for example because it was issued by an earlier version of this package; the user must then log in again.

attributes, if any, restricts the query to those attributes, as for ServiceProvider.MakeAttributeQuery. The result describes the user; it does not authenticate them.

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. If Session implements SessionTerminator, the sessions the request names are also ended there, as for a request sent with the SOAP binding, so that other copies of the session, in other browsers, are refused too: those with one of its SessionIndexes or, if it has none, every session of its NameID issued before it. A session provider that cannot do that (ErrSessionTerminationUnsupported) only has the browser's session deleted, as before; any other error ending them is passed to OnError, whose response is discarded, and the IDP is still answered with Success, since the session of the browser it sent has ended.

A POST with Content-Type text/xml is a LogoutRequest sent with the SOAP binding (back-channel single logout, saml-profiles §4.4): the IDP sends it itself, without the browser. It must be signed by the IDP (see saml.ServiceProvider.ValidateSOAPLogoutRequest). Once it is validated, the sessions it names are ended with the session provider's TerminateSessions (see SessionTerminator), and the IDP is answered with a signed LogoutResponse with the status Success, or Responder if Session does not implement SessionTerminator or could not end them. An invalid SOAP request is passed to OnError, whose response is discarded, and answered with a SOAP Fault. To have the IDP use it, advertise the SOAP binding in the SP metadata (see Options.LogoutBindings).

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 are the bindings the SP metadata advertises for its
	// SingleLogoutService, SloURL. If empty, HTTP-POST is advertised.
	//
	// Add saml.SOAPBinding to let the IdP end sessions with back-channel
	// LogoutRequests (see Middleware.ServeSLO). It is not advertised by
	// default: an IdP that sees it may prefer it to the browser bindings,
	// and it ends sessions only if the session provider can end them on the
	// server, which the default one does with a store in memory that a
	// single process sees (see SessionRevocations).
	LogoutBindings []string

	// RejectUnknownConditions sets
	// saml.ServiceProvider.RejectUnknownConditions: if true, an assertion
	// whose Conditions holds a condition this package does not understand is
	// refused, as saml-core §2.5.1.1 requires. It is off by default.
	RejectUnknownConditions bool

	// RequireSignedResponseForCBC sets
	// saml.ServiceProvider.RequireSignedResponseForCBC: if true, an
	// EncryptedAssertion encrypted with a CBC block cipher is decrypted
	// only if the Response carrying it is signed, as the saml-core errata
	// (E93) recommend. It is off by default.
	RequireSignedResponseForCBC bool

	// LimitRelayStateLength sets saml.ServiceProvider.LimitRelayStateLength:
	// if true, a RelayStateFunc result or other RelayState the middleware
	// would send that is longer than saml.MaxRelayStateLength (80 bytes) is
	// refused. It is off by default.
	LimitRelayStateLength bool

	// RequireStandardArtifacts sets
	// saml.ServiceProvider.RequireStandardArtifacts: if true, a SAMLart that
	// is not a type 0x0004 artifact, or whose SourceID is not the SHA-1 hash
	// of the IdP's entityID, is refused without contacting the IdP. It is
	// off by default.
	RequireStandardArtifacts bool

	// 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. saml.SOAPBinding sends the
	// LogoutRequests of HandleStartLogout from the server (back-channel
	// single logout) when the IDP supports it. See Middleware.LogoutBinding.
	// (The bindings this SP advertises for receiving logout messages are set
	// by LogoutBindings.)
	LogoutBinding string

	// KeyAttributesByName keys the session's attributes by their SAML Name
	// rather than their FriendlyName (JWTSessionCodec.KeyAttributesByName).
	// It is off by default.
	KeyAttributesByName bool

	// SignLogout signs the LogoutRequests and LogoutResponses the
	// middleware sends with Key, even if SignRequest is not set
	// (saml.ServiceProvider.LogoutSignatureMethod). The single logout
	// profile requires them to be signed with the HTTP-Redirect and HTTP-POST
	// bindings (saml-profiles §4.4.3.1 and §4.4.3.4). With SignRequest they
	// are signed anyway. It is off by default.
	SignLogout bool

	// 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

	// RejectExpiredIDPMetadata, if true, refuses messages from the IDP once
	// the validUntil of IDPMetadata has passed. It is off by default. See
	// saml.ServiceProvider.RejectExpiredIDPMetadata.
	RejectExpiredIDPMetadata 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

	// SessionRevocations, if set, is where the default session provider
	// records the sessions ended by back-channel single logout, and checks
	// each session it reads. If nil, DefaultSessionProvider uses a
	// MemorySessionRevocationStore of DefaultMaxSessionRevocations records,
	// which serves a single process only. Applications served by several
	// processes must set a store they share; see SessionRevocationStore.
	SessionRevocations SessionRevocationStore
}

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 RevocableSession added in v0.6.2

type RevocableSession interface {
	SessionWithNameID

	// GetSessionIssuedAt returns when the session was issued.
	GetSessionIssuedAt() time.Time
}

RevocableSession is a session that a CookieSessionProvider can check against its Revocations: it knows the NameID of its user and when it was issued. If it also implements SessionWithAttributes, the values of its "SessionIndex" attribute are its SessionIndexes. JWTSessionClaims implements it; a custom SessionCodec must make sessions that implement it, and declare so by implementing RevocableSessionCodec, for back-channel single logout to end them.

type RevocableSessionCodec added in v0.6.2

type RevocableSessionCodec interface {
	SessionCodec

	// RevocableSessions reports whether every Session that Decode returns
	// implements RevocableSession, with the NameID value and (as the
	// "SessionIndex" attribute of SessionWithAttributes) the SessionIndexes
	// of the assertion it was made from, and the time it was issued. These
	// must be protected from change by the client, as the signature of a
	// JWT protects them.
	RevocableSessions() bool
}

RevocableSessionCodec is a SessionCodec that declares whether the sessions it decodes can be checked against the Revocations of a CookieSessionProvider. CookieSessionProvider.TerminateSessions ends sessions only when its Codec implements it and RevocableSessions reports true: otherwise GetSession could not refuse the sessions it records, and the IdP would be told that they had ended when they had not.

JWTSessionCodec implements it. A custom SessionCodec whose sessions implement RevocableSession should implement it too.

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 SessionRevocationStore added in v0.6.2

type SessionRevocationStore interface {
	// Revoke records that the sessions with key issued at or before
	// revokedAt are revoked. If key is already recorded, the later of the
	// two times is kept. The record is needed until expiresAt, when every
	// such session has expired, and may be dropped after that.
	Revoke(ctx context.Context, key string, revokedAt, expiresAt time.Time) error

	// RevokedAt returns the time recorded for key, or the zero time if
	// none is recorded (or its record has expired).
	RevokedAt(ctx context.Context, key string) (time.Time, error)
}

SessionRevocationStore records revoked sessions for a CookieSessionProvider. Each record has a key, which names either every session of a user or the sessions of a user with a given SessionIndex, and a time: sessions with that key issued at or before it are revoked.

Implementations must be safe for concurrent use. MemorySessionRevocationStore keeps records in memory, for a single server; deployments with several servers must share the records between them, for example in a database or a cache server, so that a session revoked by the server that received the IdP's LogoutRequest is refused by all of them.

Keys are at most 80 bytes of ASCII letters, digits and colons.

type SessionTerminator added in v0.6.2

type SessionTerminator interface {
	// TerminateSessions ends the sessions that req, a LogoutRequest from
	// the IdP that has been validated, names (saml-core §3.7.1): those of
	// its NameID with one of its SessionIndexes or, if it has none, every
	// session of its NameID. Sessions made after it returns are not
	// affected. It returns an error if it could not end them all.
	TerminateSessions(ctx context.Context, req *saml.LogoutRequest) error
}

SessionTerminator is implemented by a SessionProvider that can end sessions on the server, without the browser that holds them. ServeSLO needs it to honor a LogoutRequest the IdP sends with the SOAP binding (back-channel single logout): no browser is involved, so the session cookie cannot be deleted, and the session must be refused the next time it is presented instead. ServeSLO also uses it for a LogoutRequest the IdP sends through the browser, to end the copies of the named sessions that other browsers hold.

CookieSessionProvider implements it when its Revocations store is set and its Codec implements RevocableSessionCodec.

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 SessionWithSAMLNameID added in v0.6.2

type SessionWithSAMLNameID interface {
	Session

	// GetSAMLNameID returns the NameID, or false if the session does not
	// record it.
	GetSAMLNameID() (saml.NameID, bool)
}

SessionWithSAMLNameID is a session that knows the full SAML NameID of the user it belongs to, with its Format and qualifiers, as the IdP issued it. Middleware.QueryAttributes needs it to name the user in an attribute query.

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