MCPcopy Create free account
hub / github.com/crewjam/saml / Example_attributes

Function Example_attributes

samlsp/example_attributes_test.go:20–56  ·  view source on GitHub ↗

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 FriendlyN

()

Source from the content-addressed store, hash-verified

18// Name when there is no FriendlyName. Which attributes are present, and what
19// they are called, is up to the identity provider.
20func Example_attributes() {
21 handler := http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
22 // A single attribute value:
23 email := samlsp.AttributeFromContext(r.Context(), "mail")
24 fmt.Println("mail:", email)
25
26 session := samlsp.SessionFromContext(r.Context())
27
28 // All values of an attribute:
29 if s, ok := session.(samlsp.SessionWithAttributes); ok {
30 fmt.Println("groups:", s.GetAttributes()["eduPersonAffiliation"])
31 }
32
33 // The NameID from the assertion's Subject:
34 if claims, ok := session.(samlsp.JWTSessionClaims); ok {
35 fmt.Println("NameID:", claims.Subject)
36 }
37 })
38
39 // In a real service, RequireAccount puts the session in the request
40 // context. Here we put one there by hand.
41 session := samlsp.JWTSessionClaims{
42 RegisteredClaims: jwt.RegisteredClaims{Subject: "jdoe@example.com"},
43 Attributes: samlsp.Attributes{
44 "mail": {"jdoe@example.com"},
45 "eduPersonAffiliation": {"member", "staff"},
46 },
47 }
48 r := httptest.NewRequest("GET", "/hello", nil)
49 r = r.WithContext(samlsp.ContextWithSession(r.Context(), session))
50 handler.ServeHTTP(httptest.NewRecorder(), r)
51
52 // Output:
53 // mail: jdoe@example.com
54 // groups: [member staff]
55 // NameID: jdoe@example.com
56}

Callers

nothing calls this directly

Calls 6

AttributeFromContextFunction · 0.92
SessionFromContextFunction · 0.92
ContextWithSessionFunction · 0.92
PrintlnMethod · 0.80
ServeHTTPMethod · 0.80
GetAttributesMethod · 0.65

Tested by

no test coverage detected