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
()
| 18 | // Name when there is no FriendlyName. Which attributes are present, and what |
| 19 | // they are called, is up to the identity provider. |
| 20 | func 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 | } |
nothing calls this directly
no test coverage detected