saml

package module
v0.15.2 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2018 License: MIT Imports: 26 Imported by: 2

README

saml

Build Status cover.run go Go Report Card GoDoc

Package saml provides tools and middleware for implementing SAML based single sign-on.

Currently, the saml package depends on the xmlsec1 command.

See _example/servers for example implementations of IdP and SP servers.

SAML SSO basics

SAML SSO process

IdP initiated SSO
  1. An user selects a service provider (SP) to log in via SSO, a typical use case for this is a login button on an intranet.
  2. The user is asked by their login details (if not within a session yet).
  3. The IdP creates an payload (AuthnRequest) containing the user information and signs it.
  4. The IdP forces the user to submit the signed request to the SP they selected. This is typically done via a FORM that is auto-submitted via JavaScript.
  5. The SP receives the message and determines if the signature is valid, among other details.
  6. If the SP decides to trust the message, it can decode the payload with is expected to contain user information, such as e-mail address, unique ID and name details.
  7. The SP uses the payload and provides access to the user.
SP initiated SSO
  1. An user tries to access a restricted URL at a SP.
  2. The SP looks up the IdP that matches the private resource and redirects the user to a special IdP page. The original URL is passed as a RelayState parameter.
  3. The user is asked by their login details.
  4. The IdP creates an payload (AuthnRequest) containing the user information and signs it.
  5. The IdP forces the user to submit the signed request to the SP they selected. This is typically done via a FORM that is auto-submitted via JavaScript.
  6. The SP receives the message and determines if the signature is valid, among other details.
  7. If the SP decides to trust the message, it can decode the payload with is expected to contain user information, such as e-mail address, unique ID and name details.
  8. The SP uses the payload, provides access to the user and follows the RelayState URL.
  9. The user gets access to the restricted URL.

License

Code that is not based on previous Open Source work is released under the MIT license:

Copyright (c) 2017 Pressly Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Other portions of the code were taken from crewjam's saml, with the following license:

Copyright (c) 2015, Ross Kinder All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Documentation

Index

Constants

View Source
const (
	// HTTPPostBinding is the official URN for the HTTP-POST binding (transport)
	HTTPPostBinding = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"

	// HTTPRedirectBinding is the official URN for the HTTP-Redirect binding (transport)
	HTTPRedirectBinding = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
)
View Source
const (
	ProtocolNamespace = "urn:oasis:names:tc:SAML:2.0:protocol"

	NameIDEntityFormat = "urn:oasis:names:tc:SAML:2.0:nameid-format:entity"

	NameIDEmailAddressFormat = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
)
View Source
const (
	CryptoSHA256 = "http://www.w3.org/2001/04/xmlenc#sha256"
)
View Source
const IssueLifetime = time.Second * 90

IssueLifetime is the maximum timeframe where an assertion can be considered valid by the receptor.

View Source
const (
	// Modified RFC3339Nano format with only 7 digits for milliseconds instead of 9 to be compatible with the Azure IdP
	SAMLTimeFormat = "2006-01-02T15:04:05.9999999Z07:00"
)

Variables

View Source
var ClockDriftTolerance = time.Duration(0)

ClockDriftTolerance is added or substracted to the current time to give some tolerance to assertion's NotBefore and NotOnOrAfter

View Source
var NewID = func() string {
	uid, _ := uuid.NewV4()
	return fmt.Sprintf("id-%x", uid)
}

NewID is a function that returns a unique identifier. This value can be overwritten during tests.

View Source
var Now = time.Now

Now is a function that returns the current time. This value can be overwritten during tests.

View Source
var StatusSuccess = "urn:oasis:names:tc:SAML:2.0:status:Success"

StatusSuccess is the value of a StatusCode element when the authentication succeeds. (nominally a constant, except for testing)

View Source
var WorkDir = "/tmp"

WorkDir is a temporary directory for files. We need to write keys to disk in order for xmlsec1 to pick them and use them.

Functions

func IsSecurityException

func IsSecurityException(err error, opts *SecurityOpts) bool

IsSecurityException returns whether the given error is a security exception not bypassed by SecurityOpts.

func ParseCacheDuration added in v0.10.0

func ParseCacheDuration(value string) (time.Duration, error)

ParseCacheDuration reads a xsd:duration from the metadata payload and converts into a time.Duration

See http://www.datypic.com/sc/xsd/t-xsd_duration.html

Types

type Assertion

type Assertion struct {
	XMLName            xml.Name  `xml:"urn:oasis:names:tc:SAML:2.0:assertion Assertion"`
	ID                 string    `xml:",attr"`
	IssueInstant       time.Time `xml:",attr"`
	Version            string    `xml:",attr"`
	Issuer             *Issuer
	Signature          *xmlsec.Signature
	Subject            *Subject
	Conditions         *Conditions
	AuthnStatement     *AuthnStatement
	AttributeStatement *AttributeStatement
}

Assertion represents the SAML object of the same name.

See http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf

type Attribute

type Attribute struct {
	FriendlyName string           `xml:",attr"`
	Name         string           `xml:",attr"`
	NameFormat   string           `xml:",attr"`
	Values       []AttributeValue `xml:"AttributeValue"`
}

Attribute represents the SAML object of the same name.

See http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf

type AttributeStatement

type AttributeStatement struct {
	Attributes []Attribute `xml:"Attribute"`
}

AttributeStatement represents the SAML object of the same name.

See http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf

type AttributeValue

type AttributeValue struct {
	Type   string `xml:"http://www.w3.org/2001/XMLSchema-instance type,attr"`
	Value  string `xml:",chardata"`
	NameID *NameID
}

AttributeValue represents the SAML object of the same name.

See http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf

type AttributesMap

type AttributesMap map[string][]string

AttributesMap is a type that provides methods for working with SAML attributes.

func NewAttributesMap

func NewAttributesMap(assertion *Assertion) *AttributesMap

NewAttributesMap creates an attribute map given a third party assertion.

func (*AttributesMap) Get

func (a *AttributesMap) Get(name string) string

Get returns the first value of the given attribute, if any.

type Audience

type Audience struct {
	Value string `xml:",chardata"`
}

Audience represents the SAML object of the same name.

See http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf

type AudienceRestriction

type AudienceRestriction struct {
	Audience *Audience
}

AudienceRestriction represents the SAML object of the same name.

See http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf

type Authenticator added in v0.9.8

type Authenticator func(w http.ResponseWriter, r *http.Request) (*Session, error)

Authenticator defines an authentication function that returns a *saml.Session value.

type AuthnContext

type AuthnContext struct {
	AuthnContextClassRef *AuthnContextClassRef
}

AuthnContext represents the SAML object of the same name.

See http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf

type AuthnContextClassRef

type AuthnContextClassRef struct {
	Value string `xml:",chardata"`
}

AuthnContextClassRef represents the SAML object of the same name.

See http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf

type AuthnRequest

type AuthnRequest struct {
	// Since multiple namespaces can be used, don't hardcode in the element
	XMLName xml.Name
	// Spec lists that the xmlns also needs to be namespaced: https://docs.oasis-open.org/security/saml/v2.0/saml-schema-protocol-2.0.xsd
	// TODO: create custom marshaler
	XMLNamespace string `xml:"xmlns:samlp,attr,omitempty"`

	Signature *xmlsec.Signature `xml:"http://www.w3.org/2000/09/xmldsig# Signature"`

	// An identifier for the request.
	// The values of the ID attribute in a request and the InResponseTo
	// attribute in the corresponding response MUST match.
	ID string `xml:",attr"`

	// The version of this request.
	// Only version 2.0 is supported by pressly/saml
	Version string `xml:",attr"`

	// The time instant of issue of the request. The time value is encoded in UTC
	IssueInstant SAMLTime `xml:",attr"`

	// Identifies the entity that generated the request message
	// By default, the value of the <Issuer> element is a URI of no more than 1024 characters.
	// Changes from SAML version 1 to 2
	// An <Issuer> element can now be present on requests and responses (in addition to appearing on assertions).
	Issuer Issuer

	// A URI reference indicating the address to which this request has been sent. This is useful to prevent
	// malicious forwarding of requests to unintended recipients, a protection that is required by some
	// protocol bindings. If it is present, the actual recipient MUST check that the URI reference identifies the
	// location at which the message was received. If it does not, the request MUST be discarded. Some
	// protocol bindings may require the use of this attribute (see [SAMLBind]).
	Destination string `xml:",attr"`

	// Specifies by value the location to which the <Response> message MUST be returned to the
	// requester. The responder MUST ensure by some means that the value specified is in fact associated
	// with the requester. [SAMLMeta] provides one possible mechanism; signing the enclosing
	// <AuthnRequest> message is another. This attribute is mutually exclusive with the
	// AssertionConsumerServiceIndex attribute and is typically accompanied by the ProtocolBinding attribute.
	AssertionConsumerServiceURL string `xml:",attr"`

	// A URI reference that identifies a SAML protocol binding to be used when returning the <Response>
	// message. See [SAMLBind] for more information about protocol bindings and URI references defined
	// for them. This attribute is mutually exclusive with the AssertionConsumerServiceIndex attribute
	// and is typically accompanied by the AssertionConsumerServiceURL attribute.
	ProtocolBinding string `xml:",attr"`

	// Specifies constraints on the name identifier to be used to represent the requested subject.
	// If omitted, then any type of identifier supported by the identity provider for the requested
	// subject can be used, constrained by any relevant deployment-specific policies, with respect to privacy.
	NameIDPolicy NameIDPolicy
}

AuthnRequest represents the SAML object of the same name, a request from a service provider to authenticate a user.

See http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf sec 3.4.1 Element <AuthnRequest>

type AuthnStatement

type AuthnStatement struct {
	AuthnInstant    time.Time `xml:",attr"`
	SessionIndex    string    `xml:",attr"`
	SubjectLocality SubjectLocality
	AuthnContext    AuthnContext
}

AuthnStatement represents the SAML object of the same name.

See http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf

type CacheDuration added in v0.10.0

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

func (*CacheDuration) Duration added in v0.10.0

func (duration *CacheDuration) Duration() time.Duration

func (*CacheDuration) MarshalAttr added in v0.10.0

func (duration *CacheDuration) MarshalAttr(name xml.Name) (xml.Attr, error)

func (*CacheDuration) UnmarshalXMLAttr added in v0.10.0

func (duration *CacheDuration) UnmarshalXMLAttr(attr xml.Attr) error

type Conditions

type Conditions struct {
	NotBefore           time.Time `xml:",attr"`
	NotOnOrAfter        time.Time `xml:",attr"`
	AudienceRestriction *AudienceRestriction
}

Conditions represents the SAML object of the same name.

See http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf

type EncryptedAssertion

type EncryptedAssertion struct {
	XMLName       xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:assertion EncryptedAssertion"`
	Assertion     *Assertion
	EncryptedData []byte `xml:",innerxml"`
}

EncryptedAssertion represents the SAML object of the same name.

See http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf

type EncryptionMethod

type EncryptionMethod struct {
	Algorithm string `xml:"Algorithm,attr"`
}

EncryptionMethod represents the XMLSEC object of the same name

type Endpoint

type Endpoint struct {
	Binding          string `xml:"Binding,attr"`
	Location         string `xml:"Location,attr"`
	ResponseLocation string `xml:"ResponseLocation,attr,omitempty"`
}

Endpoint represents the SAML EndpointType object.

See http://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf section 2.2.2

type EntitiesDescriptor

type EntitiesDescriptor struct {
	XMLName          xml.Name    `xml:"urn:oasis:names:tc:SAML:2.0:metadata EntitiesDescriptor"`
	EntityDescriptor []*Metadata `xml:"urn:oasis:names:tc:SAML:2.0:metadata EntityDescriptor"`
}

EntitiesDescriptor represents the SAML object of the same name.

See http://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf section 2.3.1

type IDPSSODescriptor

type IDPSSODescriptor struct {
	XMLName                    xml.Name        `xml:"urn:oasis:names:tc:SAML:2.0:metadata IDPSSODescriptor"`
	ProtocolSupportEnumeration string          `xml:"protocolSupportEnumeration,attr"`
	KeyDescriptor              []KeyDescriptor `xml:"KeyDescriptor"`
	NameIDFormat               []string        `xml:"NameIDFormat"`
	SingleSignOnService        []Endpoint      `xml:"SingleSignOnService"`
}

IDPSSODescriptor represents the SAML IDPSSODescriptorType object.

See http://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf section 2.4.3

type IdentityProvider

type IdentityProvider struct {

	// Identifier of the IdP entity  (must be a URI)
	EntityID string

	MetadataURL string

	SSOURL string

	SecurityOpts

	// File system location of the private key file
	KeyFile string

	// File system location of the cert file
	CertFile string

	// Private key can also be provided as a param
	// For now we need to write to a temp file since xmlsec requires a physical file to validate the document signature
	PrivkeyPEM string

	// Cert can also be provided as a param
	// For now we need to write to a temp file since xmlsec requires a physical file to validate the document signature
	PubkeyPEM string

	// Service provide settings
	SPMetadataURL string
	SPMetadata    *Metadata

	SPAcsURL string
	// contains filtered or unexported fields
}

IdentityProvider represents an identity provider.

func (*IdentityProvider) Cert

func (idp *IdentityProvider) Cert() (*pem.Block, error)

Cert returns a *pem.Block value that corresponds to the IdP's certificate.

func (*IdentityProvider) GenerateResponse added in v0.12.0

func (idp *IdentityProvider) GenerateResponse(samlRequest, relayState string, sess *Session, address string) ([]byte, error)

func (*IdentityProvider) GetSPCertFile

func (idp *IdentityProvider) GetSPCertFile() (string, error)

GetSPCertFile returns a physical path where the SP's certificate can be accessed.

func (*IdentityProvider) GetSPMetadata

func (idp *IdentityProvider) GetSPMetadata() (*Metadata, error)

GetSPMetadata returns a the SP's metadata value

func (*IdentityProvider) Metadata

func (idp *IdentityProvider) Metadata() (*Metadata, error)

Metadata returns a metadata value based on the IdP's data.

func (*IdentityProvider) MetadataHandler added in v0.9.8

func (idp *IdentityProvider) MetadataHandler(w http.ResponseWriter, r *http.Request)

MetadataHandler generates and serves the IdP's metadata.xml file.

func (*IdentityProvider) NewLoginRequest added in v0.9.8

func (idp *IdentityProvider) NewLoginRequest(spMetadataURL string, authFn Authenticator) (*LoginRequest, error)

NewLoginRequest creates a login request against an SP.

func (*IdentityProvider) PrivkeyFile

func (idp *IdentityProvider) PrivkeyFile() (string, error)

PrivkeyFile returns a physical path where the IdP's key can be accessed.

func (*IdentityProvider) PubkeyFile

func (idp *IdentityProvider) PubkeyFile() (string, error)

PubkeyFile returns a physical path where the IdP's public key can be accessed.

type IdpAuthnRequest

type IdpAuthnRequest struct {
	IDP *IdentityProvider

	// Address set in the SubjectConfirmation element of the Assertion
	Address string

	RelayState              string
	RequestBuffer           []byte
	Request                 AuthnRequest
	ServiceProviderMetadata *Metadata
	ACSEndpoint             *IndexedEndpoint
	Assertion               *Assertion
	AssertionBuffer         []byte
	Response                *Response
}

IdpAuthnRequest is used by IdentityProvider to handle a single authentication request.

func (*IdpAuthnRequest) MakeAssertion

func (req *IdpAuthnRequest) MakeAssertion(session *Session) error

MakeAssertion produces a SAML assertion for the given request and assigns it to req.Assertion.

func (*IdpAuthnRequest) MakeResponse

func (req *IdpAuthnRequest) MakeResponse() error

MakeResponse computes the Response field of the IdpAuthnRequest

func (*IdpAuthnRequest) MarshalAssertion

func (req *IdpAuthnRequest) MarshalAssertion() error

MarshalAssertion produces a valid and signed XML assertion.

type IndexedEndpoint

type IndexedEndpoint struct {
	Binding  string `xml:"Binding,attr"`
	Location string `xml:"Location,attr"`
	Index    int    `xml:"index,attr"`
}

IndexedEndpoint represents the SAML IndexedEndpointType object.

See http://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf section 2.2.3

type Issuer

type Issuer struct {
	XMLName xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:assertion Issuer"`
	Format  string   `xml:",attr"`
	Value   string   `xml:",chardata"`
}

Issuer represents the SAML object of the same name.

See http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf

type KeyDescriptor

type KeyDescriptor struct {
	Use               string             `xml:"use,attr"`
	KeyInfo           KeyInfo            `xml:"http://www.w3.org/2000/09/xmldsig# KeyInfo"`
	EncryptionMethods []EncryptionMethod `xml:"EncryptionMethod"`
}

KeyDescriptor represents the XMLSEC object of the same name

type KeyInfo

type KeyInfo struct {
	XMLName     xml.Name `xml:"http://www.w3.org/2000/09/xmldsig# KeyInfo"`
	Certificate string   `xml:"X509Data>X509Certificate"`
}

KeyInfo represents the XMLSEC object of the same name

type LoginRequest added in v0.9.8

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

LoginRequest represents a login request that the IdP creates in order to try autenticating against a SP.

func (*LoginRequest) PostForm added in v0.9.8

func (lr *LoginRequest) PostForm(w http.ResponseWriter, r *http.Request)

PostForm creates and serves a form that is used to authenticate to the SP.

type Metadata

type Metadata struct {
	XMLName          xml.Name          `xml:"urn:oasis:names:tc:SAML:2.0:metadata EntityDescriptor"`
	ValidUntil       time.Time         `xml:"validUntil,attr"`
	CacheDuration    *CacheDuration    `xml:"cacheDuration,attr,omitempty"`
	EntityID         string            `xml:"entityID,attr"`
	SPSSODescriptor  *SPSSODescriptor  `xml:"SPSSODescriptor"`
	IDPSSODescriptor *IDPSSODescriptor `xml:"IDPSSODescriptor"`
}

Metadata represents the SAML EntityDescriptor object.

See http://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf section 2.3.2

func GetMetadata

func GetMetadata(metadataURL string) (*Metadata, error)

GetMetadata takes the URL of a metadata.xml file, downloads and parses it. Returns a *Metadata value.

func (*Metadata) Cert added in v0.12.0

func (metadata *Metadata) Cert() string

func (*Metadata) SSOService added in v0.12.0

func (metadata *Metadata) SSOService(binding string) *Endpoint

type NameID

type NameID struct {
	Format          string `xml:",attr"`
	NameQualifier   string `xml:",attr"`
	SPNameQualifier string `xml:",attr"`
	Value           string `xml:",chardata"`
}

NameID represents the SAML object of the same name.

See http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf

type NameIDPolicy

type NameIDPolicy struct {
	XMLName xml.Name

	// 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. Defaults to "false". When "false", the
	// requester constrains the identity provider to only issue an assertion to it if an acceptable identifier for
	// the principal has already been established. Note that this does not prevent the identity provider from
	// creating such identifiers outside the context of this specific request (for example, in advance for a
	// large number of principals)
	AllowCreate bool `xml:",attr"`

	// Specifies the URI reference corresponding to a name identifier format defined in this or another
	// specification (see Section 8.3 for examples). The additional value of
	// urn:oasis:names:tc:SAML:2.0:nameid-format:encrypted is defined specifically for use
	// within this attribute to indicate a request that the resulting identifier be encrypted
	Format string `xml:",attr"`
}

NameIDPolicy represents the SAML object of the same name.

See http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf Also refer to Azure docs for their IdP supported values: https://msdn.microsoft.com/en-us/library/azure/dn195589.aspx

type Response

type Response struct {
	XMLName xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:protocol Response"`

	// An identifier for the request.
	// The values of the ID attribute in a request and the InResponseTo
	// attribute in the corresponding response MUST match.
	ID string `xml:",attr"`

	// The version of this request.
	// Only version 2.0 is supported by pressly/saml
	Version string `xml:",attr"`

	// The time instant of issue of the request. The time value is encoded in UTC
	IssueInstant time.Time `xml:",attr"`

	// A code representing the status of the corresponding reques
	Status *Status

	// A URI reference indicating the address to which this request has been sent. This is useful to prevent
	// malicious forwarding of requests to unintended recipients, a protection that is required by some
	// protocol bindings. If it is present, the actual recipient MUST check that the URI reference identifies the
	// location at which the message was received. If it does not, the request MUST be discarded. Some
	// protocol bindings may require the use of this attribute
	Destination string `xml:",attr"`

	// An XML Signature that authenticates the requester and provides message integrity
	Signature *xmlsec.Signature

	// A reference to the identifier of the request to which the response corresponds, if any. If the response
	// is not generated in response to a request, or if the ID attribute value of a request cannot be
	// determined (for example, the request is malformed), then this attribute MUST NOT be present.
	// Otherwise, it MUST be present and its value MUST match the value of the corresponding request's
	// ID attribute.
	InResponseTo string `xml:",attr"`

	// Identifies the entity that generated the request message
	// By default, the value of the <Issuer> element is a URI of no more than 1024 characters.
	// Changes from SAML version 1 to 2
	// An <Issuer> element can now be present on requests and responses (in addition to appearing on assertions).
	Issuer *Issuer

	EncryptedAssertion *EncryptedAssertion

	Assertion *Assertion
}

Response represents the SAML object of the same name.

See http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf section 3.2

type SAMLTime added in v0.15.1

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

func NewSAMLTime added in v0.15.1

func NewSAMLTime(t time.Time) SAMLTime

The JSON and XML marshallers use the RFC3339Nano by default, which states that the milliseconds part of the date can have up to 9 digits: 2006-01-02T15:04:05.999999999Z07:00 The Azure IdP expects the AuthnRequest IssueInstant to confirm with the RoundTrip "O" ISO 8601 format (https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings#Roundtrip) Since the RFC3339Nano formats the date with 9 digits for milliseconds, the Azure IdP returns an error since only up to 7 digits are allowed. NOTE: the docs list that ActiveDirectory expects the field, however, doesn't evaluate it (https://docs.microsoft.com/en-us/previous-versions/azure/dn195589(v=azure.100))

To ensure the date conforms with the Azure IdP, a new SAMLTime is implemented with a marshaller capping the number if milliseconds up to 7

func (SAMLTime) MarshalXMLAttr added in v0.15.1

func (samlTime SAMLTime) MarshalXMLAttr(name xml.Name) (xml.Attr, error)

func (SAMLTime) Time added in v0.15.1

func (samlTime SAMLTime) Time() time.Time

func (SAMLTime) UnmarshalXMLAttr added in v0.15.1

func (samlTime SAMLTime) UnmarshalXMLAttr(attr xml.Attr) error

type SPSSODescriptor

type SPSSODescriptor struct {
	XMLName                    xml.Name          `xml:"urn:oasis:names:tc:SAML:2.0:metadata SPSSODescriptor"`
	AuthnRequestsSigned        bool              `xml:",attr"`
	WantAssertionsSigned       bool              `xml:",attr"`
	ProtocolSupportEnumeration string            `xml:"protocolSupportEnumeration,attr"`
	KeyDescriptor              []KeyDescriptor   `xml:"KeyDescriptor"`
	ArtifactResolutionService  []IndexedEndpoint `xml:"ArtifactResolutionService"`
	SingleLogoutService        []Endpoint        `xml:"SingleLogoutService"`
	ManageNameIDService        []Endpoint
	NameIDFormat               []string          `xml:"NameIDFormat"`
	AssertionConsumerService   []IndexedEndpoint `xml:"AssertionConsumerService"`
	AttributeConsumingService  []interface{}
}

SPSSODescriptor represents the SAML SPSSODescriptorType object.

See http://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf section 2.4.2

type SecurityOpts

type SecurityOpts struct {
	AllowSelfSignedCert   bool
	TrustUnknownAuthority bool
}

SecurityOpts allows to bypass some security checks.

type ServiceProvider

type ServiceProvider struct {
	MetadataURL string

	// Identifier of the SP entity  (must be a URI)
	EntityID string

	// Assertion Consumer Service URL
	// Specifies where the <AuthnResponse> message MUST be returned to
	ACSURL string

	// SAML protocol binding to be used when returning the <Response> message.
	// Supports only HTTP-POST binding
	ACSBinding string

	AllowIdpInitiated bool

	SecurityOpts

	// File system location of the private key file
	KeyFile string

	// File system location of the cert file
	CertFile string

	// Private key can also be provided as a param
	// For now we need to write to a temp file since xmlsec requires a physical file to validate the document signature
	PrivkeyPEM string

	// Cert can also be provided as a param
	// For now we need to write to a temp file since xmlsec requires a physical file to validate the document signature
	PubkeyPEM string

	DTDFile string

	// Identity Provider settings the Service Provider instance should use
	IdPMetadataURL string
	IdPMetadataXML []byte
	IdPMetadata    *Metadata

	// Identifier of the SP entity (must be a URI)
	IdPEntityID string

	// File system location of the cert file
	IdPCertFile string
	// Cert can also be provided as a param
	// For now we need to write to a temp file since xmlsec requires a physical file to validate the document signature
	IdPPubkeyPEM string

	// SAML protocol binding to be used when sending the <AuthnRequest> message
	IdPSSOServiceBinding string

	// URL Target of the IdP where the SP will send the AuthnRequest message
	IdPSSOServiceURL string

	// Whether to sign the SAML Request sent to the IdP to initiate the SSO workflow
	IdPSignSAMLRequest bool
	// contains filtered or unexported fields
}

ServiceProvider represents a service provider.

func (*ServiceProvider) AssertResponse added in v0.11.0

func (sp *ServiceProvider) AssertResponse(base64Res string) (*Assertion, error)

AssertResponse parses and validates a SAML response and its assertion

func (*ServiceProvider) Cert

func (sp *ServiceProvider) Cert() (*pem.Block, error)

Cert returns a *pem.Block value that corresponds to the SP's certificate.

func (*ServiceProvider) GetIdPCertFile

func (sp *ServiceProvider) GetIdPCertFile() (string, error)

GetIdPCertFile returns a physical path where the IdP certificate can be accessed.

func (*ServiceProvider) Metadata

func (sp *ServiceProvider) Metadata() (*Metadata, error)

Metadata returns a metadata value based on the SP's data.

func (*ServiceProvider) MetadataXML added in v0.11.0

func (sp *ServiceProvider) MetadataXML() ([]byte, error)

MetadataXML returns SAML 2.0 Service Provider metadata XML.

func (*ServiceProvider) NewAuthnRequest added in v0.11.0

func (sp *ServiceProvider) NewAuthnRequest() (*AuthnRequest, error)

NewAuthnRequest creates a new AuthnRequest object for the given IdP URL.

func (*ServiceProvider) ParseIdPMetadata added in v0.12.0

func (sp *ServiceProvider) ParseIdPMetadata() (*Metadata, error)

func (*ServiceProvider) PrivkeyFile

func (sp *ServiceProvider) PrivkeyFile() (string, error)

PrivkeyFile returns a physical path where the SP's key can be accessed.

func (*ServiceProvider) PubkeyFile

func (sp *ServiceProvider) PubkeyFile() (string, error)

PubkeyFile returns a physical path where the SP's public certificate can be accessed.

func (*ServiceProvider) SAMLRequest added in v0.13.0

func (sp *ServiceProvider) SAMLRequest(relayState string) (string, error)

SAMLRequest creates a new AuthnRequest object to be sent to the IdP Depending on the selected binding a HTTP-POST form, or a HTTP-Redirect URL are returned

func (*ServiceProvider) SAMLRequestForm added in v0.13.0

func (sp *ServiceProvider) SAMLRequestForm(authnRequest []byte, relayState string) (string, error)

SAMLRequestForm creates a HTML form with an embedded SAML Request

func (*ServiceProvider) SAMLRequestURL added in v0.13.0

func (sp *ServiceProvider) SAMLRequestURL(authnRequest []byte, relayState string) (string, error)

SAMLRequestURL builds a HTTP Redirect SAML Request URL aka SP-initiated login (SP->IdP). The data is passed in the ?SAMLRequest query parameter and the value is base64 encoded and deflate-compressed <AuthnRequest> XML element. The final redirect destination that will be invoked on successful login is passed using ?RelayState query parameter.

TODO(diogo): HTTP-Redirect signed requests

type Session

type Session struct {
	ID         string
	CreateTime time.Time
	ExpireTime time.Time
	Index      string

	NameID         string
	Groups         []string
	UserID         string
	UserFullname   string
	UserName       string
	UserEmail      string
	UserCommonName string
	UserSurname    string
	UserGivenName  string
}

Session represents a user session. It is returned by the SessionProvider implementation's GetSession method. Fields here are used to set fields in the SAML assertion.

type Status

type Status struct {
	XMLName    xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:protocol Status"`
	StatusCode StatusCode
}

Status represents the SAML object of the same name.

See http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf

type StatusCode

type StatusCode struct {
	XMLName xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:protocol StatusCode"`
	Value   string   `xml:",attr"`
}

StatusCode represents the SAML object of the same name.

See http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf

type Subject

type Subject struct {
	XMLName             xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:assertion Subject"`
	NameID              *NameID
	SubjectConfirmation *SubjectConfirmation
}

Subject represents the SAML object of the same name.

See http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf

type SubjectConfirmation

type SubjectConfirmation struct {
	Method                  string `xml:",attr"`
	SubjectConfirmationData SubjectConfirmationData
}

SubjectConfirmation represents the SAML object of the same name.

See http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf

type SubjectConfirmationData

type SubjectConfirmationData struct {
	Address      string    `xml:",attr"`
	InResponseTo string    `xml:",attr"`
	NotOnOrAfter time.Time `xml:",attr"`
	Recipient    string    `xml:",attr"`
}

SubjectConfirmationData represents the SAML object of the same name.

See http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf

type SubjectLocality

type SubjectLocality struct {
	Address string `xml:",attr"`
}

SubjectLocality represents the SAML object of the same name.

See http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf

Directories

Path Synopsis
_example
Package xmlsec is a wrapper around the xmlsec1 command https://www.aleksey.com/xmlsec/index.html
Package xmlsec is a wrapper around the xmlsec1 command https://www.aleksey.com/xmlsec/index.html

Jump to

Keyboard shortcuts

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