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 ¶
- Variables
- func AttributeFromContext(ctx context.Context, name string) string
- func ContextWithSession(ctx context.Context, session Session) context.Context
- func DefaultOnError(w http.ResponseWriter, _ *http.Request, err error)
- func DefaultServiceProvider(opts Options) saml.ServiceProvider
- func FetchMetadata(ctx context.Context, httpClient *http.Client, metadataURL url.URL) (*saml.EntityDescriptor, error)
- func FetchMetadataByEntityID(ctx context.Context, httpClient *http.Client, metadataURL url.URL, ...) (*saml.EntityDescriptor, error)
- func ParseMetadata(data []byte) (*saml.EntityDescriptor, error)
- func ParseMetadataByEntityID(data []byte, entityID string) (*saml.EntityDescriptor, error)
- func RequireAttribute(name, value string) func(http.Handler) http.Handler
- type AssertionHandler
- type Attributes
- type CookieRequestTracker
- func (t CookieRequestTracker) GetTrackedRequest(r *http.Request, index string) (*TrackedRequest, error)
- func (t CookieRequestTracker) GetTrackedRequests(r *http.Request) []TrackedRequest
- func (t CookieRequestTracker) StopTrackingRequest(w http.ResponseWriter, r *http.Request, index string) error
- func (t CookieRequestTracker) TrackRequest(w http.ResponseWriter, r *http.Request, samlRequestID string) (string, error)
- type CookieSessionProvider
- type ErrorFunction
- type JWTSessionClaims
- type JWTSessionCodec
- type JWTTrackedRequestClaims
- type JWTTrackedRequestCodec
- type Middleware
- func (m *Middleware) CreateSessionFromAssertion(w http.ResponseWriter, r *http.Request, assertion *saml.Assertion, ...)
- func (m *Middleware) HandleStartAuthFlow(w http.ResponseWriter, r *http.Request)
- func (m *Middleware) HandleStartLogout(w http.ResponseWriter, r *http.Request)
- func (m *Middleware) RequireAccount(handler http.Handler) http.Handler
- func (m *Middleware) ServeACS(w http.ResponseWriter, r *http.Request)
- func (m *Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (m *Middleware) ServeMetadata(w http.ResponseWriter, _ *http.Request)
- func (m *Middleware) ServeSLO(w http.ResponseWriter, r *http.Request)
- type NopAssertionHandler
- type Options
- type RequestTracker
- type Session
- type SessionCodec
- type SessionProvider
- type SessionWithAttributes
- type SessionWithNameID
- type TrackedRequest
- type TrackedRequestCodec
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrNoSession = errors.New("saml: session not present")
ErrNoSession is the error returned when the remote user does not have a session
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.
Functions ¶
func AttributeFromContext ¶ added in v0.4.0
AttributeFromContext is a convenience method that returns the named attribute from the session, if available.
func ContextWithSession ¶ added in v0.4.0
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.
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 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>.
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 RequireAttribute ¶
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
AssertionHandler is an interface implemented by types that can handle assertions and add extra functionality
type Attributes ¶
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 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.
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
func (s JWTTrackedRequestCodec) Encode(value TrackedRequest) (string, error)
Encode returns an encoded string representing the TrackedRequest.
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
}
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 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 either the HTTP-Redirect or the HTTP-POST 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
// 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
}
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:
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.
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 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
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
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.