### Install with Composer Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/README.md Install the bundle using Composer. Requires Symfony 5 or earlier. ```bash composer require hslavich/oneloginsaml-bundle ``` -------------------------------- ### Full example: hslavich_onelogin_saml configuration Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/configuration.md Complete YAML configuration for the OneLogin SAML bundle, covering idp, sp, baseurl, strict, debug, security, contactPerson, and organization. Use as a template for your own setup. ```yaml hslavich_onelogin_saml: idp: entityId: 'http://id.example.com/saml2/idp/metadata.php' singleSignOnService: url: 'http://id.example.com/saml2/idp/SSOService.php' binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect' singleLogoutService: url: 'http://id.example.com/saml2/idp/SingleLogoutService.php' binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect' x509cert: '' sp: entityId: 'http://myapp.com/app_dev.php/saml/metadata' assertionConsumerService: url: 'http://myapp.com/app_dev.php/saml/acs' binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST' singleLogoutService: url: 'http://myapp.com/app_dev.php/saml/logout' binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect' privateKey: '' baseurl: 'http://myapp.com' strict: true debug: true security: nameIdEncrypted: false authnRequestsSigned: false logoutRequestSigned: false logoutResponseSigned: false wantMessagesSigned: false wantAssertionsSigned: false wantNameIdEncrypted: false requestedAuthnContext: true # or an array: [foo, bar] signMetadata: false wantXMLValidation: true relaxDestinationValidation: false destinationStrictlyMatches: true rejectUnsolicitedResponsesWithInResponseTo: false signatureAlgorithm: 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256' digestAlgorithm: 'http://www.w3.org/2001/04/xmlenc#sha256' contactPerson: technical: { givenName: 'Tech User', emailAddress: 'techuser@example.com' } support: { givenName: 'Support User', emailAddress: 'supportuser@example.com' } administrative: { givenName: 'Administrative User', emailAddress: 'administrativeuser@example.com' } organization: en: name: 'Example' displayname: 'Example' url: 'http://example.com' ``` -------------------------------- ### SAML Login Link in Template Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/README.md Add a link to the saml_login route in your login page to start SAML sign-on. ```html SAML Login ``` -------------------------------- ### GET/POST /saml/login Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/endpoints.md Initiates the SAML login flow, redirecting the user to the IdP for authentication. This endpoint accepts both GET and POST requests. ```APIDOC ## [GET/POST] /saml/login ### Description Initiates the SAML login flow, redirecting the user to the IdP for authentication. This endpoint accepts both GET and POST requests. ### Method GET, POST ### Endpoint /saml/login ### Parameters No parameters documented. ### Request Body No request body documented. ### Response No response details documented. ``` -------------------------------- ### GET /saml/login Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/README.md Initiates SP-initiated SSO by redirecting the user to the identity provider's login page. Optionally accepts a RelayState parameter to specify the post-login redirect target. ```APIDOC ## [GET] /saml/login ### Description Initiates SP-initiated SSO by redirecting the user to the identity provider's login page. Optionally accepts a RelayState parameter to specify the post-login redirect target. ### Method GET ### Endpoint /saml/login ### Parameters #### Query Parameters - **RelayState** (string) - Optional - The URL to redirect to after successful authentication ### Response #### Success Response (302) - **Location** (string) - Redirect to the IdP login URL ``` -------------------------------- ### SamlUserFactory constructor signature Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlUserFactory.md Constructor for the default JIT user factory. Requires the FQCN of the user class and a mapping array of user properties to literal values or SAML attributes (strings starting with '$'). ```php public function __construct(string $userClass, array $mapping) ``` -------------------------------- ### loginAction(Request $request) Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlController.md Starts the SAML single sign-on flow by redirecting the user to the IdP login page. Reads the target path from the session and delegates to the OneLogin SAML library. ```APIDOC ## [POST] /saml/login ### Description Starts the SAML single sign-on flow by redirecting the user to the IdP login page. Reads the target path from the session and delegates to the OneLogin SAML library. ### Method POST ### Endpoint /saml/login ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (302) Redirect to the IdP SSO URL. #### Response Example None ### Error Handling - **RuntimeException** - When the session holds an authentication error. ``` -------------------------------- ### GET|POST /saml/login (saml_login) Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/endpoints.md Starts the SP-initiated single sign-on flow by redirecting the browser to the IdP SSO URL. This endpoint is public and must be accessible without authentication to avoid redirect loops. ```APIDOC ## GET|POST /saml/login (saml_login) ### Description Starts the SP-initiated single sign-on flow. Redirects the browser to the IdP SSO URL. ### Method GET|POST ### Endpoint /saml/login ### Parameters #### Session - **session** (—) - Required - Must exist (the action reads `_firewall_context` request attribute and `_security..target_path` session key to compute the return URL) #### Request Body - **`_security.last_error`** (`\Exception` serialized) - Optional - Set by the failure handler; when present, the action rethrows its message as `\RuntimeException` ### Response #### Success Response (302) Result of `\OneLogin\Saml2\Auth::login($targetPath)` — a `RedirectResponse` to the IdP `singleSignOnService.url` (HTTP-Redirect binding), carrying the signed `SAMLRequest` (when `security.authnRequestsSigned`) and `RelayState`. #### Error Response (500) When a previous authentication error was stored in the session (converted to `\RuntimeException`). ### Auth Public (must be in `access_control` with `PUBLIC_ACCESS`, otherwise the login redirect loops). The entry-point path — `SamlAuthenticator::start()` redirects unauthenticated users to this route (`login_path` option). ``` -------------------------------- ### Get Attributes from User Object Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/README.md After injecting SAML attributes, you can retrieve them from the user object. ```php $email = $this->getUser()->getEmail(); ``` -------------------------------- ### User entity implementing UserInterface Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlUserProvider.md Example user class for the SAML provider. The constructor must accept (string $username, array $roles) because SamlUserProvider calls new $userClass($identifier, $defaultRoles). ```php roles = $roles; } public function getRoles(): array { return $this->roles; } public function getUserIdentifier(): string { return $this->username; } // eraseCredentials(), etc. } ``` -------------------------------- ### Configure SAML on a firewall Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlFactory.md YAML configuration for enabling SAML authentication on a firewall, including provider setup, access control, and logout. Options like username_attribute, use_attribute_friendly_name, check_path, failure_path, always_use_default_target_path are demonstrated; failure_path and always_use_default_target_path come from failure-handler and success-handler defaults respectively. ```yaml security: enable_authenticator_manager: true providers: saml_provider: saml: user_class: 'App\Entity\User' default_roles: ['ROLE_USER'] firewalls: app: pattern: ^/ saml: username_attribute: uid use_attribute_friendly_name: true check_path: saml_acs login_path: saml_login failure_path: saml_login always_use_default_target_path: true remember_me: true logout: path: saml_logout access_control: - { path: ^/saml/login, roles: PUBLIC_ACCESS } - { path: ^/saml/metadata, roles: PUBLIC_ACCESS } - { path: ^/, roles: ROLE_USER } ``` -------------------------------- ### GET /saml/metadata Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/endpoints.md Exposes the Service Provider (SP) SAML metadata document, to be registered on the IdP side. This endpoint is publicly accessible and returns the SP metadata XML. ```APIDOC ## [GET] /saml/metadata ### Description Exposes the Service Provider (SP) SAML metadata document, to be registered on the IdP side. This endpoint is publicly accessible and returns the SP metadata XML. ### Method GET ### Endpoint /saml/metadata ### Parameters No parameters. ### Response #### Success Response (200) - **Content-Type**: `xml` - **Body**: `\OneLogin\Saml2\Auth::getSettings()->getSPMetadata()` — the SP metadata XML #### Response Example ```xml ... ``` ### Errors Errors thrown during metadata generation by OneLogin itself (e.g. missing `sp.entityId` in settings) — not caught by the controller. ``` -------------------------------- ### Service configuration for SamlUserFactory with mapping Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlUserFactory.md YAML service definition showing how to configure the factory with a user class and a mapping. Values starting with '$' reference SAML attributes; others are literal values. ```yaml services: my_user_factory: class: Hslavich\OneloginSamlBundle\Security\User\SamlUserFactory arguments: - App\Entity\User - password: 'notused' # literal value email: $mail # from SAML attribute 'mail' name: $cn # from SAML attribute 'cn' roles: ['ROLE_USER'] # literal array ``` -------------------------------- ### Reading SAML data from the token in a controller Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlToken.md Example controller method that retrieves the security token, checks for SamlTokenInterface, and reads attributes, sessionIndex, and user identifier. ```php // Inside a controller after SAML login use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; class ProfileController extends AbstractController { public function profile(): \Symfony\Component\HttpFoundation\Response { $token = $this->container->get('security.token_storage')->getToken(); if ($token instanceof \Hslavich\OneloginSamlBundle\Security\Http\Authenticator\Token\SamlTokenInterface) { $attributes = $token->getAttributes(); // full SAML attribute map $sessionIndex = $token->getAttribute('sessionIndex'); $username = $token->getUserIdentifier(); } return $this->json(['username' => $username ?? null, 'sessionIndex' => $sessionIndex ?? null]); } } ``` -------------------------------- ### Redirect user to IdP via saml_login route Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlController.md Shows a controller action that redirects to the 'saml_login' route, which triggers the SamlController::loginAction. The bundle routes SSO automatically, so this is an alternative way to start SSO through Symfony's route handling. ```php // Any controller in your app use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\Routing\Annotation\Route; class LoginController { #[Route('/sso', name: 'start_sso')] public function startSso(): RedirectResponse { // The bundle routes starting SSO as well; this shows calling saml_login // through Symfony's route handling (uses SamlController::loginAction). return $this->redirectToRoute('saml_login'); } } ``` -------------------------------- ### GET /saml/metadata Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlController.md Returns the SAML metadata XML for the service provider. This endpoint is used to expose SP metadata to identity providers. ```APIDOC ## [GET] /saml/metadata ### Description Returns the SAML metadata XML for the service provider. This endpoint is used to expose SP metadata to identity providers. ### Method GET ### Endpoint /saml/metadata ### Parameters No parameters. ### Response #### Success Response (200) - **Content-Type**: `xml` - **Body**: The SP metadata XML string. #### Response Example ```xml ... ``` ``` -------------------------------- ### GET/POST /saml/logout Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/endpoints.md Handles the SAML single logout service, processing logout requests and responses. This endpoint accepts both GET and POST requests. ```APIDOC ## [GET/POST] /saml/logout ### Description Handles the SAML single logout service, processing logout requests and responses. This endpoint accepts both GET and POST requests. ### Method GET, POST ### Endpoint /saml/logout ### Parameters No parameters documented. ### Request Body No request body documented. ### Response No response details documented. ``` -------------------------------- ### Example User entity implementing SamlUserInterface Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/types.md Shows a concrete implementation of SamlUserInterface in an App\Entity\User class. The setSamlAttributes() method assigns the email from the SAML attributes array. The class must also implement getUserIdentifier() and getRoles() from UserInterface. ```php namespace App\Entity; use Hslavich\OneloginSamlBundle\Security\User\SamlUserInterface; use Symfony\Component\Security\Core\User\UserInterface; class User implements SamlUserInterface { protected $username; protected $email; public function setSamlAttributes(array $attributes) { $this->email = $attributes['mail'][0]; } // getUserIdentifier(), getRoles(), ... from UserInterface } ``` -------------------------------- ### JIT factory decision comment (PHP) Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/errors.md Cases 11/12: notes that UserNotFoundException is converted to provisioning only when a user_factory is configured; entity provider required for JIT. ```php // Cases 11/12 — JIT factory decision // In SamlAuthenticator the provider's UserNotFoundException is only converted // into provisioning when a user_factory is configured; otherwise it bubbles up. // An entity provider (doctrine) is required for JIT provisioning // (SamlUserProvider never throws UserNotFoundException). ``` -------------------------------- ### Custom User Factory Implementation Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/README.md Create your own user factory by implementing SamlUserFactoryInterface. ```php setRoles(['ROLE_USER']); $user->setUsername($username); $user->setPassword('notused'); $user->setEmail($attributes['mail'][0]); $user->setName($attributes['cn'][0]); return $user; } } ``` -------------------------------- ### Security Configuration for Just-in-Time User Provisioning Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/README.md Configure the firewall to provision a new user from SAML attributes when the user provider cannot find a user. ```yaml security: # ... providers: saml_provider: # Loads user from user repository entity: class: App\Entity\User property: username firewalls: default: provider: saml_provider saml: username_attribute: uid # User factory service user_factory: my_user_factory logout: path: saml_logout ``` -------------------------------- ### User Factory Service Configuration Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/README.md Create the user factory service in services.yaml. Fields with '$' reference SAML attribute values. ```yaml services: my_user_factory: class: Hslavich\OneloginSamlBundle\Security\User\SamlUserFactory arguments: # User class - App\Entity\User # Attribute mapping. - password: 'notused' email: $mail name: $cn lastname: $sn roles: ['ROLE_USER'] ``` -------------------------------- ### Configure firewall and user provider in security.yaml Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/README.md Configure the SAML firewall and user provider. The provider instantiates a user with default roles. The firewall matches SAML attribute 'uid' with username, uses friendlyName, and sets check_path and login_path. ```yaml security: # ... providers: saml_provider: # Basic provider instantiates a user with default roles saml: user_class: 'AppBundle\Entity\User' default_roles: ['ROLE_USER'] firewalls: app: pattern: ^/ saml: # Match SAML attribute 'uid' with username. # Uses getNameId() method by default. username_attribute: uid # Use the attribute's friendlyName instead of the name use_attribute_friendly_name: true check_path: saml_acs login_path: saml_login logout: path: saml_logout access_control: - { path: ^/saml/login, roles: PUBLIC_ACCESS } - { path: ^/saml/metadata, roles: PUBLIC_ACCESS } - { path: ^/, roles: ROLE_USER } ``` -------------------------------- ### Enable bundle in config/bundles.php Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/README.md Enable the bundle in the Symfony application. Only needed if not using Symfony Flex. ```php return [ // ... Hslavich\OneloginSamlBundle\HslavichOneloginSamlBundle::class => ['all' => true], ] ``` -------------------------------- ### Basic SAML firewall configuration in security.yaml Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlAuthenticator.md Configures the SAML authenticator for a firewall, setting the username attribute, check path, and login path. Requires the enable_authenticator_manager flag and a SAML provider with user class and default roles. Access control grants public access to login and metadata routes. ```yaml # config/packages/security.yaml security: enable_authenticator_manager: true providers: saml_provider: saml: user_class: 'App\Entity\User' default_roles: ['ROLE_USER'] firewalls: app: pattern: ^/ saml: username_attribute: uid check_path: saml_acs login_path: saml_login logout: path: saml_logout access_control: - { path: ^/saml/login, roles: PUBLIC_ACCESS } - { path: ^/saml/metadata, roles: PUBLIC_ACCESS } - { path: ^/, roles: ROLE_USER } ``` -------------------------------- ### Custom User Factory Service Configuration Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/README.md Register your custom user factory service in services.yaml. ```yaml services: my_user_factory: class: App\Security\UserFactory ``` -------------------------------- ### Routing Configuration for SAML SP Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/README.md Add this YAML configuration to your routing file to enable the SAML service provider routes. ```yaml hslavich_saml_sp: resource: "@HslavichOneloginSamlBundle/Resources/config/routing.yml" ``` -------------------------------- ### Security Configuration for SAML and Form Login Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/README.md Integrate SAML authentication with a traditional login form by editing security.yaml. ```yaml security: enable_authenticator_manager: true providers: user_provider: # Loads user from user repository entity: class: App:User property: username firewalls: default: saml: username_attribute: uid check_path: saml_acs login_path: saml_login failure_path: saml_login always_use_default_target_path: true # Traditional login form form_login: login_path: /login check_path: /login_check always_use_default_target_path: true logout: path: saml_logout ``` -------------------------------- ### Configure SAML firewall with just-in-time provisioning Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlAuthenticator.md YAML configuration for the SAML firewall in security.yaml, enabling just-in-time provisioning with error handling. Sets username attribute, user factory, and failure path to redirect to login on authentication failure. ```yaml # config/packages/security.yaml security: enable_authenticator_manager: true providers: user_provider: entity: class: App\Entity\User property: username firewalls: default: saml: username_attribute: uid user_factory: my_user_factory check_path: saml_acs login_path: saml_login failure_path: saml_login always_use_default_target_path: true logout: path: saml_logout ``` ```yaml # config/services.yaml services: my_user_factory: class: Hslavich\OneloginSamlBundle\Security\User\SamlUserFactory arguments: - App\Entity\User - email: $mail # '$' prefix reads the SAML attribute value name: $cn roles: ['ROLE_USER'] ``` -------------------------------- ### Configure SAML metadata in hslavich_onelogin_saml.yaml Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/README.md Configure SAML metadata for IdP and SP. Optional settings include security, contactPerson, and organization. Leave out contactPerson or organization if not needed. ```yaml hslavich_onelogin_saml: # Basic settings idp: entityId: 'http://id.example.com/saml2/idp/metadata.php' singleSignOnService: url: 'http://id.example.com/saml2/idp/SSOService.php' binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect' singleLogoutService: url: 'http://id.example.com/saml2/idp/SingleLogoutService.php' binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect' x509cert: '' sp: entityId: 'http://myapp.com/app_dev.php/saml/metadata' assertionConsumerService: url: 'http://myapp.com/app_dev.php/saml/acs' binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST' singleLogoutService: url: 'http://myapp.com/app_dev.php/saml/logout' binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect' privateKey: '' # Optional settings baseurl: 'http://myapp.com' strict: true debug: true security: nameIdEncrypted: false authnRequestsSigned: false logoutRequestSigned: false logoutResponseSigned: false wantMessagesSigned: false wantAssertionsSigned: false wantNameIdEncrypted: false requestedAuthnContext: true signMetadata: false wantXMLValidation: true relaxDestinationValidation: false destinationStrictlyMatches: true rejectUnsolicitedResponsesWithInResponseTo: false signatureAlgorithm: 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256' digestAlgorithm: 'http://www.w3.org/2001/04/xmlenc#sha256' contactPerson: technical: givenName: 'Tech User' emailAddress: 'techuser@example.com' support: givenName: 'Support User' emailAddress: 'supportuser@example.com' administrative: givenName: 'Administrative User' emailAddress: 'administrativeuser@example.com' organization: en: name: 'Example' displayname: 'Example' url: 'http://example.com' ``` -------------------------------- ### Old createUser Signature for Versions Prior to 2.1 Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/README.md For versions prior to 2.1, the createUser signature was different. ```php public function createUser(SamlTokenInterface $token): UserInterface { $username = $token->getUsername(); $attributes = $token->getAttributes(); ... } ``` -------------------------------- ### Security Configuration for Persisting User Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/README.md Edit firewall settings in security.yaml to persist the user on creation and SAML attribute injection. ```yaml security: # ... firewalls: # ... default: saml: # ... persist_user: true ``` -------------------------------- ### Expose SP metadata programmatically via Auth service Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlController.md Shows how to obtain the SP metadata XML using the OneLogin Auth service's getSettings()->getSPMetadata() method. This is not typical because SamlController::metadataAction is already routed at /saml/metadata, but it demonstrates using the bundled services directly. ```php use Hslavich\OneloginSamlBundle\Controller\SamlController; use OneLogin\Saml2\Auth; class MetadataController { public function __construct(private SamlController $samlController) {} // Not typical — SamlController::metadataAction is already routed at /saml/metadata. // This shows how to obtain the same raw metadata via the bundled services: public function metadata(Auth $samlAuth) { return new \Symfony\Component\HttpFoundation\Response( $samlAuth->getSettings()->getSPMetadata(), headers: ['Content-Type' => 'xml'], ); } } ``` -------------------------------- ### User Class Implementing SamlUserInterface Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/README.md Your user class must implement SamlUserInterface to inject SAML attributes into the User object. ```php email = $attributes['mail'][0]; } } ``` -------------------------------- ### Creating a SamlToken in SamlAuthenticator::createToken() Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlToken.md Shows how SamlAuthenticator builds a SamlToken with user, firewall name, roles, and SAML attributes from SamlAttributesBadge. ```php return new SamlToken( $passport->getUser(), $firewallName, $passport->getUser()->getRoles(), $badge->getAttributes(), // SamlAttributesBadge ); ``` -------------------------------- ### Import SAML SP routing configuration Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/endpoints.md Add this YAML to your routing configuration to import the bundle's four SAML routes (saml_metadata, saml_acs, saml_login, saml_logout). Place it in config/routing.yml or config/routes.yaml. ```yaml # config/routing.yml or config/routes.yaml hslavich_saml_sp: resource: "@HslavichOneloginSamlBundle/Resources/config/routing.yml" ``` -------------------------------- ### Configure failure_handler in security.yaml Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/errors.md YAML configuration for the app firewall's saml settings, setting failure_handler to the custom SamlFailureHandler service. ```yaml security: firewalls: app: saml: check_path: saml_acs login_path: saml_login failure_handler: App\Security\SamlFailureHandler ``` -------------------------------- ### Register bundle in config/bundles.php Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/HslavichOneloginSamlBundle.md Adds the bundle to the Symfony application for all environments. ```php // config/bundles.php return [ // ... Hslavich\OneloginSamlBundle\HslavichOneloginSamlBundle::class => ['all' => true], ]; ``` -------------------------------- ### Import SAML routes in routing.yml Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlController.md Import the bundle's routing configuration to expose the four SAML endpoints. Add this to your application's routing file. ```yaml # config/routing.yml or routes.yaml hslavich_saml_sp: resource: "@HslavichOneloginSamlBundle/Resources/config/routing.yml" ``` -------------------------------- ### Error handling when constructing SamlUserProvider Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlUserProvider.md Shows how to catch InvalidArgumentException when the user class does not implement UserInterface, and how loadUserByIdentifier and refreshUser behave. refreshUser returns the same instance for a valid user and throws UnsupportedUserException for an invalid one. ```php use Hslavich\OneloginSamlBundle\Security\User\SamlUserProvider; try { $provider = new SamlUserProvider('App\Entity\NotAUser', ['ROLE_USER']); } catch (\InvalidArgumentException $e) { // "The $userClass argument must be a class implementing the UserInterface interface." error_log($e->getMessage()); } $user = $provider->loadUserByIdentifier('alice'); // new User('alice', ['ROLE_USER']) $user = $provider->refreshUser($user); // same instance returned try { $provider->refreshUser(new \stdClass()); } catch (\Symfony\Component\Security\Core\Exception\UnsupportedUserException $e) { // not an instance of the configured user class } ``` -------------------------------- ### Custom SAML failure handler service (PHP) Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/errors.md Implements AuthenticationFailureHandlerInterface to handle SAML authentication failures (cases 6, 7, 11, 12, 13, 14). Logs the exception message and redirects to /saml/login. ```php namespace App\Security; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface; class SamlFailureHandler implements AuthenticationFailureHandlerInterface { public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response { // Covers cases 6, 7, 11, 12, 13, 14 during authentication error_log('[saml] auth failed: '.$exception->getMessage()); return new RedirectResponse('/saml/login'); } } ``` -------------------------------- ### SamlToken::__construct Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlToken.md Creates a new SamlToken instance for an authenticated user. It initializes the token with the user, firewall name, roles, and SAML attributes, and sets the attributes on the token. ```APIDOC ## SamlToken::__construct ### Description Creates a new SamlToken instance for an authenticated user. It initializes the token with the user, firewall name, roles, and SAML attributes, and sets the attributes on the token. ### Method Constructor ### Signature ```php public function __construct(UserInterface $user, string $firewallName, array $roles, array $attributes) ``` ### Parameters - `$user` (UserInterface) - Required - The authenticated user - `$firewallName` (string) - Required - The firewall the token belongs to - `$roles` (array) - Required - Roles assigned to the user - `$attributes` (array) - Required - SAML attributes stored as token attributes (includes the `sessionIndex` key) ### Behavior Calls `parent::__construct($user, $firewallName, $roles)` then `$this->setAttributes($attributes)`. ### Returns Token instance (implicit). ``` -------------------------------- ### Security access_control recommended configuration Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/endpoints.md Recommended access control rules for SAML endpoints. Grants PUBLIC_ACCESS to /saml/login and /saml/metadata, and requires ROLE_USER for all other paths. ```yaml security: access_control: - { path: ^/saml/login, roles: PUBLIC_ACCESS } - { path: ^/saml/metadata, roles: PUBLIC_ACCESS } - { path: ^/, roles: ROLE_USER } ``` -------------------------------- ### Direct usage of SamlUserFactory with error handling Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlUserFactory.md Instantiates SamlUserFactory directly with an entity class and attribute mapping, then calls createUser with a username and attributes. A TypeError is caught when a referenced SAML attribute is missing, and the error is logged. ```php use Hslavich\OneloginSamlBundle\Security\User\SamlUserFactory; $factory = new SamlUserFactory( \App\Entity\User::class, ['email' => '$mail', 'active' => true], ); try { $user = $factory->createUser('alice', ['mail' => ['alice@example.com']]); // $user->getEmail() === 'alice@example.com' // $user->getActive() === true } catch (\TypeError $e) { // thrown when a referenced SAML attribute (e.g. 'mail') is missing error_log('Missing SAML attribute: '.$e->getMessage()); } ``` -------------------------------- ### Configuration Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlUserProvider.md Configuration options for the SamlUserProvider, declared by SamlUserProviderFactory::addConfiguration(). ```APIDOC ## Configuration ### Description Configuration options for the SamlUserProvider, declared by `SamlUserProviderFactory::addConfiguration()`. ### Configuration Keys - `user_class` (string) - Required (cannot be empty) - User class FQCN implementing `UserInterface` - `default_roles` (array of scalars) - Optional - Default: `['ROLE_USER']` - Roles for loaded users ### Example ```yaml security: providers: saml_provider: saml: user_class: 'App\Entity\User' default_roles: ['ROLE_USER'] ``` ``` -------------------------------- ### SamlToken constructor Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlToken.md Constructor for the SamlToken class. Requires a UserInterface instance, the firewall name, an array of roles, and an array of SAML attributes (including the 'sessionIndex' key). Calls the parent constructor and then sets the attributes. ```php public function __construct(UserInterface $user, string $firewallName, array $roles, array $attributes) ``` -------------------------------- ### SamlUserProvider constructor signature Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlUserProvider.md Constructor for SamlUserProvider. Requires a user class FQCN implementing UserInterface and an array of default roles. Throws InvalidArgumentException if the class does not implement UserInterface. ```php /** * @param class-string $userClass * @param string[] $defaultRoles */ public function __construct(string $userClass, array $defaultRoles) ``` -------------------------------- ### createUser method signature Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlUserFactory.md Creates a new user instance from the username and SAML attributes. Accepts a legacy SamlTokenInterface as the username for backward compatibility, triggering a deprecation. ```php public function createUser($username, array $attributes = []): UserInterface ``` -------------------------------- ### loadUserByUsername(string $username): UserInterface Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlUserProvider.md Legacy adapter method that loads a user by username. It delegates to loadUserByIdentifier($username). ```APIDOC ## loadUserByUsername(string $username): UserInterface ### Description Legacy adapter (see symfony/symfony#41493). Loads a user by username, delegating to `loadUserByIdentifier($username)`. ### Method `loadUserByUsername` ### Parameters - `$username` (string) - Required - The username ### Returns `UserInterface` - delegates to `loadUserByIdentifier($username)`. ``` -------------------------------- ### SamlUserFactory::__construct Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlUserFactory.md Constructor for the SamlUserFactory class. Initializes the factory with the user class to instantiate and a mapping of user properties to SAML attributes or literal values. ```APIDOC ## SamlUserFactory::__construct ### Description Constructor for the SamlUserFactory class. Initializes the factory with the user class to instantiate and a mapping of user properties to SAML attributes or literal values. ### Method Constructor ### Signature ```php public function __construct(string $userClass, array $mapping) ``` ### Parameters - `$userClass` (string) - Required - FQCN of the user class to instantiate - `$mapping` (array) - Required - Map of `userProperty => value`; when the value is a string starting with `$`, it refers to a SAML attribute ### Example ```yaml services: my_user_factory: class: Hslavich\OneloginSamlBundle\Security\User\SamlUserFactory arguments: - App\Entity\User - password: 'notused' # literal value email: $mail # from SAML attribute 'mail' name: $cn # from SAML attribute 'cn' roles: ['ROLE_USER'] # literal array ``` ### Source `Security/User/SamlUserFactory.php` lines 13–16. ``` -------------------------------- ### Validate SamlUserProvider class early (PHP) Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/errors.md Case 4: instantiates SamlUserProvider with a wrong class to trigger InvalidArgumentException early, catching misconfiguration. ```php // Case 4 — validate the configured class early use Hslavich\OneloginSamlBundle\Security\User\SamlUserProvider; try { new SamlUserProvider('App\Entity\WrongClass', ['ROLE_USER']); } catch (\InvalidArgumentException $e) { // misconfiguration } ``` -------------------------------- ### createToken(Passport $passport, string $firewallName): TokenInterface Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlAuthenticator.md Creates a new SamlToken from the given passport and firewall name. Throws a LogicException if the passport lacks a SamlAttributesBadge. ```APIDOC ## createToken(Passport $passport, string $firewallName): TokenInterface ### Description Creates a new `SamlToken` from the given passport and firewall name. Throws a `LogicException` if the passport lacks a `SamlAttributesBadge`. ### Method createToken ### Parameters - **$passport** (`Symfony\Component\Security\Http\Authenticator\Passport\Passport`) - Required - The passport carrying the user and badges - **$firewallName** (`string`) - Required - The firewall name stored in the token ### Returns `TokenInterface` - a new `Hslavich\OneloginSamlBundle\Security\Http\Authenticator\Token\SamlToken` constructed with `($passport->getUser(), $firewallName, $passport->getUser()->getRoles(), $badge->getAttributes())`. ### Throws `LogicException` - when the passport has no `SamlAttributesBadge` (message `Passport should contains a "Hslavich\OneloginSamlBundle\Security\Http\Authenticator\Passport\Badge\SamlAttributesBadge" badge.`). ``` -------------------------------- ### build(ContainerBuilder $container): void Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/HslavichOneloginSamlBundle.md Registers the security factories and compiler pass for the OneLogin SAML integration. This method is called during the Symfony container compilation process. ```APIDOC ## build(ContainerBuilder $container): void ### Description Registers the security factories and compiler pass for the OneLogin SAML integration. This method is called during the Symfony container compilation process. ### Method build ### Endpoint Hslavich\OneloginSamlBundle\HslavichOneloginSamlBundle::build ### Parameters #### Parameters - **$container** (Symfony\Component\DependencyInjection\ContainerBuilder) - Required - The container being compiled ### Returns void ### Details Registers: 1. `Hslavich\OneloginSamlBundle\DependencyInjection\Security\Factory\SamlFactory` as an authenticator factory. 2. `Hslavich\OneloginSamlBundle\DependencyInjection\Security\Factory\SamlUserProviderFactory` as a user provider factory. 3. `Hslavich\OneloginSamlBundle\DependencyInjection\Compiler\SecurityCompilerPass` as a compiler pass. ``` -------------------------------- ### SamlController constructor signature Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlController.md Constructor for SamlController, requiring the OneLogin SAML Auth instance. The service is autowired. ```php public function __construct(\OneLogin\Saml2\Auth $samlAuth) ``` -------------------------------- ### onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlAuthenticator.md Delegates to the injected success handler. When the default SamlAuthenticationSuccessHandler is used, the target URL logic honors always_use_default_target_path and the RelayState request parameter. ```APIDOC ## onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response ### Description Delegates to the injected success handler. When the default `SamlAuthenticationSuccessHandler` is used, the target URL logic honors `always_use_default_target_path` and the `RelayState` request parameter. ### Method onAuthenticationSuccess ### Parameters - `Request $request` (Request) - Required - The request object. - `TokenInterface $token` (TokenInterface) - Required - The authentication token. - `string $firewallName` (string) - Required - The firewall name. ### Returns `?Response` - The response object or null. ``` -------------------------------- ### SamlUserProvider::__construct Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlUserProvider.md Instantiates the default user provider for the SAML authentication flow. It requires a user class implementing UserInterface and a list of default roles to assign to every loaded user. ```APIDOC ## SamlUserProvider::__construct ### Description Instantiates the default user provider for the SAML authentication flow. It requires a user class implementing UserInterface and a list of default roles to assign to every loaded user. ### Method Constructor ### Signature ```php public function __construct(string $userClass, array $defaultRoles) ``` ### Parameters - `$userClass` (string, class-string) - Required - FQCN of the user entity; must implement `Symfony\Component\Security\Core\User\UserInterface`. - `$defaultRoles` (string[]) - Required - Roles assigned to every loaded user. ### Throws - `\InvalidArgumentException` - When `$userClass` is not a class implementing `UserInterface` (message: `The $userClass argument must be a class implementing the Symfony\Component\Security\Core\User\UserInterface interface.`). ### Source `Security/User/SamlUserProvider.php` lines 18–26. ``` -------------------------------- ### Basic service configuration for SamlUserFactory Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlUserFactory.md Defines a service named my_user_factory using Hslavich\OneloginSamlBundle\Security\User\SamlUserFactory with arguments for the entity class and attribute mapping. The mapping uses $mail, $cn, and $sn to reference SAML attributes, and roles is set to a literal array. ```yaml services: my_user_factory: class: Hslavich\OneloginSamlBundle\Security\User\SamlUserFactory arguments: - App\Entity\User - email: $mail name: $cn lastname: $sn roles: ['ROLE_USER'] ``` -------------------------------- ### GET|POST /saml/logout (saml_logout) Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/endpoints.md Handles single logout (SLO) for both SP-initiated and IdP-initiated flows. The firewall logout must be enabled and the listener only processes requests when the current token is a SamlTokenInterface. ```APIDOC ## GET|POST /saml/logout (saml_logout) ### Description Single logout (SLO) endpoint. Handles both SP-initiated logout (firewall `logout.path` points here; `SamlLogoutListener` runs `processSLO()` or issues `\OneLogin\Saml2\Auth::logout()`) and IdP-initiated SLO (IdP sends `SAMLRequest`/`SAMLResponse` messages here; `idp.singleLogoutService` must be symmetric). ### Method GET|POST ### Endpoint /saml/logout ### Response Redirect to the IdP SLO URL or the app's logout target, depending on flow; the session is cleared by the security logout. ### Errors If the controller action itself is reached, it throws `\RuntimeException('You must activate the logout in your security firewall configuration.')` — meaning processing was not intercepted by the listener. ### Auth The firewall logout must be enabled (`logout: { path: saml_logout }`); the `SamlLogoutListener` no-ops when the current token is not a `SamlTokenInterface`. ``` -------------------------------- ### onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/SamlAuthenticator.md Delegates to the injected failure handler. ```APIDOC ## onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response ### Description Delegates to the injected failure handler. ### Method onAuthenticationFailure ### Parameters - `Request $request` (Request) - Required - The request object. - `AuthenticationException $exception` (AuthenticationException) - Required - The authentication exception. ### Returns `?Response` - The response object or null. ``` -------------------------------- ### LegacySamlUserFactoryInterface::createUser Source: https://github.com/hslavich/oneloginsamlbundle/blob/2.x/_autodocs/api-reference/LegacySecurityApi.md Defines the contract for creating a user from a SAML token. This method is deprecated since version 2.1 and is used for backward compatibility. ```APIDOC ## LegacySamlUserFactoryInterface::createUser ### Description Defines the contract for creating a user from a SAML token. This method is deprecated since version 2.1 and is used for backward compatibility. ### Method createUser ### Signature public function createUser(SamlTokenInterface $token) ### Parameters - **$token** (SamlTokenInterface) - Required - The SAML token containing user information. ### Returns - The created user object (type not specified in source). ### Deprecation Deprecated since 2.1. Use the modern user factory instead. ```