# `ExSaml.SPHandler`
[🔗](https://github.com/docJerem/ex_saml/blob/main/lib/ex_saml/sp_handler.ex#L1)

Handles Service Provider SAML responses: metadata generation, assertion consumption,
and logout handling.

## Functions

  * `send_metadata/1` - Returns SP metadata XML for the given IdP
  * `consume_signin_response/2` - Processes the IdP sign-in response and returns the assertion
  * `handle_logout_response/1` - Processes the IdP logout response
  * `handle_logout_request/1` - Processes an IdP-initiated logout request

# `consume_signin_response`

Processes the IdP sign-in response and extracts the SAML assertion.

On success returns
`{:ok, %{flow: flow, assertion: assertion, nonce: nonce, user_token: token, redirect_uri: uri}}`
where:

  * `flow` is `:idp_initiated` or `:sp_initiated` and reflects which SAML flow
    produced the response (deduced from the assertion's `SubjectConfirmationData`
    `InResponseTo` — empty means IdP-initiated).
  * `nonce` is the AuthnRequest-bound SAML nonce for SP-initiated flows, and
    `nil` for IdP-initiated flows (no AuthnRequest exists in that case, so no
    nonce is generated; downstream consumers must accept `nil` for the
    IdP-initiated case).

On failure returns `{:error, reason}`. Possible reasons include
`:idp_initiated_not_allowed`, `:invalid_target_url`, `:invalid_relay_state`,
`:invalid_idp_id`, and `:access_denied`.

# `consume_signin_response`

# `handle_logout_request`

Handles an IdP-initiated logout request.

# `handle_logout_response`

Processes the IdP logout response and redirects to the target URL.

# `send_metadata`

Returns the SP metadata XML for the IdP in `conn.private[:ex_saml_idp]`.

# `target_url`

Returns the fallback target URL from application config (defaults to `"/"`).

# `target_url`

Returns the target URL from session or relay state cache, falling back
to `target_url/0` (`Application.get_env(:ex_saml, :fallback_target_url, "/")`)
when neither is set. Never returns `nil` — callers can safely pass the
result to `Plug.Conn.put_resp_header/3`.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
