saml

package module
v0.0.0-...-8c4d3db Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2024 License: MPL-2.0 Imports: 25 Imported by: 0

README

saml package

Go Reference

A package for writing clients that integrate with SAML Providers.

The SAML library orients mainly on the implementation profile for federation interoperability (also known as interoperable SAML), a set of software conformance requirements intended to facilitate interoperability within the context of full mesh identity federations. It supports the Web Browser SSO profile with HTTP-Post and HTTP-Redirect as supported service bindings. The default SAML settings follow the requirements of the interoperable SAML deployment profile.

Example usage

    // Create a new saml config providing the necessary provider information:
    cfg, err := saml.NewConfig(<entityID>, <acs>, <metadata>, options...)
	// handle error

    // Use the config to create the service provider:
    sp, err := saml.NewServiceProvider(cfg)
    // handle error

    // With the service provider you can create saml authentication requests:

    // Generate a saml auth request with HTTP Post-Binding
    template, err := sp.AuthRequestPost("relay state", options...)
    // handle error

    // Generate a saml auth request with HTTP Request-Binding
    redirectURL, err := sp.AuthRequestRedirect("relay state", options...)
    // handle error

    // Parsing a SAML response:
    r.ParseForm()
    samlResp := r.PostForm.Get("SAMLResponse")

    response, err := sp.ParseResponse(samlResp, "Response ID", options...)
    // handle error

You can find the full demo code in the saml/demo package.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInternal             = errors.New("internal error")
	ErrBindingUnsupported   = errors.New("Configured binding unsupported by the IDP")
	ErrInvalidTLSCert       = errors.New("invalid tls certificate")
	ErrInvalidParameter     = errors.New("invalid parameter")
	ErrMissingAssertions    = errors.New("missing assertions")
	ErrInvalidTime          = errors.New("invalid time")
	ErrInvalidAudience      = errors.New("invalid audience")
	ErrMissingSubject       = errors.New("subject missing")
	ErrMissingAttributeStmt = errors.New("attribute statement missing")
)

Functions

func ApplyOpts

func ApplyOpts(opts interface{}, opt ...Option)

ApplyOpts takes a pointer to the options struct as a set of default options and applies the slice of opts as overrides.

func DefaultGenerateAuthRequestID

func DefaultGenerateAuthRequestID() (string, error)

DefaultGenerateAuthRequestID generates an auth XSD:ID conform ID. A UUID prefixed with an underscore.

func Deflate

func Deflate(authn *core.AuthnRequest, opt ...Option) ([]byte, error)

Deflate returns an AuthnRequest in the Deflate file format, applying default compression.

func WritePostBindingRequestHeader

func WritePostBindingRequestHeader(w http.ResponseWriter) error

WritePostBindingRequestHeader writes recommended content headers when using the SAML HTTP POST binding.

Types

type Config

type Config struct {
	// AssertionConsumerServiceURL defines the endpoint at the service provider where
	// the identity provider will redirect to with its authentication response. Must be
	// a valid URL. Required.
	AssertionConsumerServiceURL string

	// EntityID is a globally unique identifier of the service provider. Must be a
	// valid URL. Required.
	EntityID string

	// MetadataURL is the endpoint an identity provider serves its metadata XML document.
	// Must be a valid URL. Takes precedence over MetadataXML and MetadataParameters.
	// Required if MetadataXML or MetadataParameters not set.
	MetadataURL string

	// MetadataXML is the XML-formatted metadata an identity provider provides to
	// configure a service provider. Takes precedence over MetadataParameters. Optional.
	MetadataXML string

	// MetadataParameters are the individual parameters an identity provider provides
	// to configure a service provider. Optional.
	MetadataParameters *MetadataParameters

	// ValidUntil is a function that defines the time after which the service provider
	// metadata document is considered invalid. Optional.
	ValidUntil ValidUntilFunc

	// GenerateAuthRequestID generates an XSD:ID conforming ID.
	GenerateAuthRequestID GenerateAuthRequestIDFunc
}

Config contains configuraiton parameters that are required for a service provider to successfully federate with an identity provider and execute a SAML authentication flow.

func NewConfig

func NewConfig(entityID, acs, metadataURL string, opt ...Option) (*Config, error)

NewConfig creates a new configuration for a service provider. Identity provider metadata can be provided via the metadataURL parameter or the WithMetadataXML and WithMetadataParameters options. The metadataURL will always take precedence if options are provided.

Options: - WithValidUntil - WithMetadataXML - WithMetadataParameters - WithGenerateAuthRequestID

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the Config fields.

type GenerateAuthRequestIDFunc

type GenerateAuthRequestIDFunc func() (string, error)

GenerateAuthRequestIDFunc represents a function that generates the SAML authentication request ID.

type MetadataParameters

type MetadataParameters struct {
	// Issuer is a globally unique identifier of the identity provider.
	// Must be a valid URL. Required.
	Issuer string

	// SingleSignOnURL is the single sign-on service URL of the identity provider.
	// Must be a valid URL. Required.
	SingleSignOnURL string

	// IDPCertificate is the PEM-encoded public key certificate provided by the identity
	// provider. Used to verify response and assertion signatures. Required.
	IDPCertificate string

	// Binding defines the binding that will be used for authentication requests. Defaults
	// to HTTP-POST binding. Optional.
	Binding core.ServiceBinding
}

MetadataParameters are parameters that are required for SAML federation. This can be used when the IDP doesn't support a Metadata URL.

func (*MetadataParameters) Validate

func (c *MetadataParameters) Validate() error

Validate validates the provided metadata parameters.

type Option

type Option func(interface{})

Option defines a common functional options type which can be used in a variadic parameter pattern.

func AllowCreate

func AllowCreate() Option

AllowCreate is a Boolean value used to indicate whether the identity provider is allowed, in the course of fulfilling the request, to create a new identifier to represent the principal.

func ForceAuthn

func ForceAuthn() Option

ForceAuthentication is a boolean value that tells the identity provider it MUST authenticate the presenter directly rather than rely on a previous security context.

func InsecureSkipAssertionConditionValidation

func InsecureSkipAssertionConditionValidation() Option

InsecureSkipAssertionConditionValidation disables/skips validation of the assertion conditions within the SAML response. This options should only be used for testing purposes.

func InsecureSkipRequestIDValidation

func InsecureSkipRequestIDValidation() Option

InsecureSkipRequestIDValidation disables/skips if the given requestID matches the InResponseTo parameter in the SAML response. This options should only be used for testing purposes.

func InsecureSkipSignatureValidation

func InsecureSkipSignatureValidation() Option

InsecureSkipSignatureValidation disables/skips validation of the SAML Response and its assertions. This options should only be used for testing purposes.

func InsecureWantAssertionsUnsigned

func InsecureWantAssertionsUnsigned() Option

InsecureWantAssertionsUnsigned provides a way to optionally request that you want insecure/unsigned assertions.

func WithACSServiceBinding

func WithACSServiceBinding(b core.ServiceBinding) Option

WithACSServiceBinding provides an optional service binding.

func WithAdditionalACSEndpoint

func WithAdditionalACSEndpoint(b core.ServiceBinding, location url.URL) Option

WithAdditionalACSEndpoint provides an optional additional ACS endpoint

func WithAssertionConsumerServiceURL

func WithAssertionConsumerServiceURL(url string) Option

WithAssertionConsumerServiceURL changes the Assertion Consumer Service URL to use in the Auth Request or during the response validation

func WithAuthContextClassRefs

func WithAuthContextClassRefs(cfs []string) Option

WithAuthContextClassRefs defines AuthnContextClassRefs. An AuthContextClassRef Specifies the requirements, if any, that the requester places on the authentication context that applies to the responding provider's authentication of the presenter.

func WithCache

func WithCache(cache bool) Option

WithCache control whether we should cache IDP Metadata.

func WithClock

func WithClock(clock clockwork.Clock) Option

WithClock changes the clock used when generating requests.

func WithGenerateAuthRequestID

func WithGenerateAuthRequestID(generateAuthRequestID GenerateAuthRequestIDFunc) Option

WithGenerateAuthRequestID provides an XSD:ID conforming ID for authentication requests

func WithIndent

func WithIndent(indent int) Option

WithIndent indent the XML document when marshalling it.

func WithMetadataNameIDFormat

func WithMetadataNameIDFormat(format ...core.NameIDFormat) Option

WithMetadataNameIDFormat provides an optional name ID formats, which are added to the existing set.

func WithMetadataParameters

func WithMetadataParameters(metadata MetadataParameters) Option

WithMetadataParameters provides optional static metadata from an identity provider that can be used to configure the service provider.

func WithMetadataXML

func WithMetadataXML(metadata string) Option

WithMetadataXML provides optional identity provider metadata in the form of an XML document that can be used to configure the service provider.

func WithNameIDFormat

func WithNameIDFormat(f core.NameIDFormat) Option

WithNameIDFormat will set an NameIDPolicy object with the given NameIDFormat. It implies allowCreate=true as recommended by the SAML 2.0 spec, which says: "Requesters that do not make specific use of this (AllowCreate) attribute SHOULD generally set it to “true” to maximize interoperability." See https://www.oasis-open.org/committees/download.php/56776/sstc-saml-core-errata-2.0-wd-07.pdf

func WithProtocolBinding

func WithProtocolBinding(binding core.ServiceBinding) Option

WithProtocolBinding defines the ProtocolBinding to be used. It defaults to HTTP-Post. The ProtocolBinding is a URI reference that identifies a SAML protocol binding to be used when returning the <Response> message.

func WithStale

func WithStale(stale bool) Option

WithStale control whether we should use a stale IDP Metadata document if refreshing it fails.

func WithValidUntil

func WithValidUntil(validUntil ValidUntilFunc) Option

WithValidUntil provides the time after which the service provider metadata document is considered invalid

type ServiceProvider

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

ServiceProvider defines a type for service providers

func NewServiceProvider

func NewServiceProvider(cfg *Config) (*ServiceProvider, error)

NewServiceProvider creates a new ServiceProvider.

func (*ServiceProvider) AuthnRequestPost

func (sp *ServiceProvider) AuthnRequestPost(
	relayState string, opt ...Option,
) ([]byte, *core.AuthnRequest, error)

AuthnRequestPost creates an AuthRequest with HTTP-Post binding.

func (*ServiceProvider) AuthnRequestRedirect

func (sp *ServiceProvider) AuthnRequestRedirect(
	relayState string, opts ...Option,
) (*url.URL, *core.AuthnRequest, error)

AuthRequestRedirect creates a SAML authentication request with HTTP redirect binding.

func (*ServiceProvider) Config

func (sp *ServiceProvider) Config() *Config

Config returns the service provider config.

func (*ServiceProvider) CreateAuthnRequest

func (sp *ServiceProvider) CreateAuthnRequest(
	id string,
	binding core.ServiceBinding,
	opt ...Option,
) (*core.AuthnRequest, error)

CreateAuthnRequest creates an Authentication Request object. The defaults follow the deployment profile for federation interoperability. See: 3.1.1 https://kantarainitiative.github.io/SAMLprofiles/saml2int.html#_service_provider_requirements [INT_SAML]

Options: - WithClock - ForceAuthn - AllowCreate - WithIDFormat - WithProtocolBinding - WithAuthContextClassRefs - WithAssertionConsumerServiceURL

func (*ServiceProvider) CreateMetadata

func (sp *ServiceProvider) CreateMetadata(opt ...Option) *metadata.EntityDescriptorSPSSO

CreateMetadata creates the metadata XML for the service provider.

Options: - InsecureWantAssertionsUnsigned - WithNameIDFormats - WithACSServiceBinding - WithAdditonalACSEndpoint

func (*ServiceProvider) IDPMetadata

func (sp *ServiceProvider) IDPMetadata(opt ...Option) (*metadata.EntityDescriptorIDPSSO, error)

IDPMetadata fetches the metadata XML document from the configured identity provider. Options: - WithClock - WithCache - WithStale

func (*ServiceProvider) ParseResponse

func (sp *ServiceProvider) ParseResponse(
	samlResp string,
	requestID string,
	opt ...Option,
) (*core.Response, error)

ParseResponse parses and validates a SAML Reponse.

Options: - InsecureSkipRequestIDValidation - InsecureSkipAssertionConditionValidation - InsecureSkipSignatureValidation - WithAssertionConsumerServiceURL - WithClock

type ValidUntilFunc

type ValidUntilFunc func() time.Time

ValidUntilFunc represents a function that sets a time until a service provider metadata document is valid.

Directories

Path Synopsis
models

Jump to

Keyboard shortcuts

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