Browse by type
Package saml contains a partial implementation of the SAML standard in golang. SAML is a standard for identity federation, i.e. either allowing a third party to authenticate your users or allowing third parties to rely on us to authenticate their users.
In SAML parlance an Identity Provider (IDP) is a service that knows how to authenticate users. A Service Provider (SP) is a service that delegates authentication to an IDP. If you are building a service where users log in with someone else's credentials, then you are a Service Provider. This package supports implementing both service providers and identity providers.
The core package contains the implementation of SAML. The package samlsp provides helper middleware suitable for use in Service Provider applications. The package samlidp provides a rudimentary IDP service that is useful for testing or as a starting point for other integrations.
Let us assume we have a simple web application to protect. We'll modify this application so it uses SAML to authenticate users.
package main
import (
"fmt"
"net/http"
)
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
}
func main() {
app := http.HandlerFunc(hello)
http.Handle("/hello", app)
http.ListenAndServe(":8000", nil)
}
Each service provider must have an self-signed X.509 key pair established. You can generate your own with something like this:
openssl req -x509 -newkey rsa:2048 -keyout myservice.key -out myservice.cert -days 365 -nodes -subj "/CN=myservice.example.com"
We will use samlsp.Middleware to wrap the endpoint we want to protect. Middleware provides both an http.Handler to serve the SAML specific URLs and a set of wrappers to require the user to be logged in. We also provide the URL where the service provider can fetch the metadata from the IDP at startup. In our case, we'll use samltest.dev, an identity provider designed for testing.
samltest.dev gives each app its own IDP, so first create an app with at least one test user. You can do this on the website or with the API:
curl -X POST https://www.samltest.dev/api/apps \
-H "Content-Type: application/json" \
-d '{"users":[{"email":"john@example.com","firstName":"John","lastName":"Doe"}]}'
The response contains the app's ID (for example app_01kg2nmcmp9gey67b0kxpqm643). The IDP metadata URL for the app is https://www.samltest.dev/apps/<APP_ID>/metadata. Download it once and keep it with the service:
curl -o idp-metadata.xml https://www.samltest.dev/apps/<APP_ID>/metadata
The IDP metadata names the certificates the service provider trusts to sign assertions, so whoever controls it controls who can log in. Loading it from a file you checked, rather than fetching it at every start, pins the IDP. See Trusting the IDP's metadata for the alternatives.
package main
import (
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"fmt"
"net/http"
"net/url"
"os"
"github.com/crewjam/saml/samlsp"
)
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", samlsp.AttributeFromContext(r.Context(), "displayName"))
}
func main() {
keyPair, err := tls.LoadX509KeyPair("myservice.cert", "myservice.key")
if err != nil {
panic(err) // TODO handle error
}
keyPair.Leaf, err = x509.ParseCertificate(keyPair.Certificate[0])
if err != nil {
panic(err) // TODO handle error
}
idpMetadataXML, err := os.ReadFile("idp-metadata.xml")
if err != nil {
panic(err) // TODO handle error
}
idpMetadata, err := samlsp.ParseMetadata(idpMetadataXML)
if err != nil {
panic(err) // TODO handle error
}
rootURL, err := url.Parse("http://localhost:8000")
if err != nil {
panic(err) // TODO handle error
}
samlSP, err := samlsp.New(samlsp.Options{
URL: *rootURL,
Key: keyPair.PrivateKey.(*rsa.PrivateKey),
Certificate: keyPair.Leaf,
IDPMetadata: idpMetadata,
})
if err != nil {
panic(err) // TODO handle error
}
app := http.HandlerFunc(hello)
http.Handle("/hello", samlSP.RequireAccount(app))
http.Handle("/saml/", samlSP)
panic(http.ListenAndServe(":8000", nil))
}
Next we'll have to register our service provider with the identity provider to establish trust from the service provider to the IDP. samltest.dev doesn't take an uploaded metadata file. Instead, set the app's SP ACS URL and SP Entity ID, either under "SAML SP Settings" on https://www.samltest.dev/apps/<APP_ID> or with the API:
curl -X PUT https://www.samltest.dev/api/apps/<APP_ID> \
-H "Content-Type: application/json" \
-d '{"users":[{"email":"john@example.com","firstName":"John","lastName":"Doe"}],
"spAcsUrl":"http://localhost:8000/saml/acs",
"spEntityId":"http://localhost:8000/saml/metadata"}'
By default samlsp uses <root URL>/saml/acs as the ACS URL and <root URL>/saml/metadata as the entity ID (set Options.AcsPath, Options.MetadataPath and Options.SloPath to use different paths). You can view the service provider's metadata at localhost:8000/saml/metadata.
Now you should be able to authenticate. The flow should look like this:
You browse to localhost:8000/hello
The middleware redirects you to https://www.samltest.dev/apps/<APP_ID>/login
samltest.dev asks which of the app's test users you want to log in as. There is no password.
samltest.dev returns you an HTML document which contains an HTML form setup to POST to localhost:8000/saml/acs. The form is automatically submitted if you have javascript enabled.
The local service validates the response, issues a session cookie, and redirects you to the original URL, localhost:8000/hello.
This time when localhost:8000/hello is requested there is a valid session and so the main content is served.
You don't need to parse the SAML response yourself. After the middleware validates it, the handlers wrapped by RequireAccount can read the user's details from the request context:
func hello(w http.ResponseWriter, r *http.Request) {
// The first value of an attribute, or "" if it is missing.
email := samlsp.AttributeFromContext(r.Context(), "mail")
session := samlsp.SessionFromContext(r.Context())
// Every attribute, with all of its values.
if s, ok := session.(samlsp.SessionWithAttributes); ok {
for name, values := range s.GetAttributes() {
fmt.Fprintf(w, "%s: %v\n", name, values)
}
}
// The NameID from the assertion's Subject, often the user's email or ID.
if claims, ok := session.(samlsp.JWTSessionClaims); ok {
fmt.Fprintf(w, "NameID: %s, email: %s\n", claims.Subject, email)
}
}
Each attribute is stored under its FriendlyName, or its Name when the IDP sends no FriendlyName (for example urn:oid:0.9.2342.19200300.100.1.3 or http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress). The IDP decides which attributes it sends and what they are called, so if one you expect is missing, check the IDP's attribute release settings. Listing every attribute as above shows exactly what you received. The SessionIndex attribute is added by this package, not sent as an attribute by the IDP.
Attributes the IDP encrypts (EncryptedAttribute) are decrypted with the service provider's key, like an encrypted assertion, and read like the others; an assertion with one that cannot be decrypted is refused. An assertion's Subject must identify the user with a NameID (possibly encrypted). One whose Subject has no identifier is refused, and so is one identified by a BaseID, unless ServiceProvider.AcceptAssertionBaseID is set: the assertion's Subject.BaseID then holds the element, which your code must interpret, and the session has no NameID.
The middleware serves the SAML Single Logout endpoint, <root URL>/saml/slo, alongside the metadata and ACS endpoints. To let users log out, route a path of your application to HandleStartLogout:
http.Handle("/saml/", samlSP)
http.HandleFunc("/logout", samlSP.HandleStartLogout)
When a user visits /logout:
HandleStartLogout deletes the session cookie and sends the browser to the IDP's SingleLogoutService with a LogoutRequest for the session's NameID and every SessionIndex of the assertion it was made from. It remembers the request's ID in a short-lived samlslo_ cookie, scoped to the SLO URL, just as login remembers the AuthnRequest. It uses the HTTP-Redirect binding if the IDP supports it, and HTTP-POST otherwise. If the IDP has no SingleLogoutService in its metadata, only the local session is ended.
The IDP ends its own session and sends a LogoutResponse back to /saml/slo.
The middleware validates the response's signature, issuer, destination and status, checks that its InResponseTo is the ID of the request it sent from this browser, and redirects the user to /. A response the SP did not ask for, or one that is replayed, is rejected.
The middleware also handles IDP initiated logout: when the IDP sends a signed LogoutRequest to /saml/slo, the middleware deletes the session cookie of that browser and answers the IDP with a LogoutResponse. With the default session provider it also records the logout in its revocation store (see Options.SessionRevocations), so that copies of the session in other browsers are refused too: those with the request's SessionIndex, or every earlier session of the user if the request names none. If that fails (for example because the store is full), the error goes to OnError and the LogoutResponse carries Success with the second-level status PartialLogout: the browser's session has ended, but its copies may not have.
For single logout to work, the IDP needs to know the SLO URL. It is in the service provider's metadata, or you can enter <root URL>/saml/slo in the IDP's settings. The SAML single logout profile requires logout requests and responses sent with the HTTP-Redirect or HTTP-POST binding to be signed, and many IDPs enforce it. They are not signed by default: set Options.SignLogout to sign them with Key (ServiceProvider.LogoutSignatureMethod), or Options.SignRequest, which signs authentication requests too. If the IDP requires the NameID to be encrypted, set ServiceProvider.EncryptLogoutNameID: the request then carries an EncryptedID, encrypted to the encryption certificate in the IDP's metadata, with the strongest cipher the metadata lists for it, AES-256-GCM if it lists none. Set ServiceProvider.LogoutNameIDEncrypter for an IDP that cannot decrypt AES-GCM. If you need different behaviour, for example to end server-side sessions, the ServiceProvider methods MakeLogoutRequest, RedirectLogoutRequestURL, ParseLogoutResponse, ValidateLogoutRequest and MakeRedirectLogoutResponse are the building blocks HandleStartLogout and ServeSLO use.
SP initiated logout can also use the SOAP binding. With Options.LogoutBinding set to saml.SOAPBinding, and an IDP whose metadata lists a SOAP SingleLogoutService, HandleStartLogout sends the signed LogoutRequest to the IDP from the server rather than through the browser (back-channel logout), deletes the session cookie and redirects the user to /. If the IDP cannot be reached or does not answer Success, the error goes to OnError, the session cookie is deleted all the same, and the browser is sent to the IDP's front-channel SingleLogoutService, if it has one, with a LogoutRequest as described above.
The service provider trusts whatever signing certificates the IDP metadata names, so get the metadata from a source you trust:
A file kept with the service, as above, checked when you download it and updated when the IDP rotates its keys.
Signed metadata. If the IDP (or its federation) signs its metadata, fetch it and check the signature against the metadata signing certificate, obtained out of band:
golang
idpMetadata, err := samlsp.FetchSignedMetadata(context.Background(), http.DefaultClient,
*idpMetadataURL, []*x509.Certificate{idpMetadataSigningCert})
Only what the signature covers is parsed. An IDP served by this package signs its metadata when IdentityProvider.SignMetadata is set.
https URL you trust, with samlsp.FetchMetadata. The metadata is then only as trustworthy as that server and its TLS certificate, and a plain http URL can be changed by anyone on the network path.Federation metadata (an <EntitiesDescriptor> such as eduGAIN or InCommon publishes) holds many IDPs. ParseMetadata and FetchMetadata refuse metadata with more than one; use ParseMetadataByEntityID, FetchMetadataByEntityID or their Signed variants to choose the IDP by its entity ID.
An IDP that is also a SAML attribute authority (for example Shibboleth) can be asked for a user's attributes outside of a login, with an AttributeQuery sent over the SOAP back channel (the Assertion Query/Request profile). This needs an AttributeAuthorityDescriptor with a SOAP AttributeService in the IDP metadata, and the IDP must be willing to answer this service provider:
```golang // The NameID the IDP issued for the user, as received at login, so that its // Format and qualifiers match what the IDP knows the user by. nameID := saml.NameID{ Format: string(saml.PersistentNameIDFormat), Value: "AAdzZWNyZXQx...", } result, err := samlSP.ServiceProvider.QueryAttributes(ctx, nameID, saml.Attribute{Name: "urn:oid:0.9.2342.19200300.100.1.3", NameForm
browse all types & interfaces →