### SAML Controller Example Source: https://github.com/saml-toolkits/ruby-saml/blob/master/README.md A full controller example for handling SAML authentication, including initialization of requests and consumption of responses. Ensure your OneLogin application uses the /saml/init and /saml/consume URLs. ```ruby # This controller expects you to use the URLs /saml/init and /saml/consume in your OneLogin application. class SamlController < ApplicationController def init request = OneLogin::RubySaml::Authrequest.new redirect_to(request.create(saml_settings)) end def consume response = OneLogin::RubySaml::Response.new(params[:SAMLResponse]) response.settings = saml_settings # We validate the SAML Response and check if the user already exists in the system if response.is_valid? # authorize_success, log the user session[:userid] = response.nameid session[:attributes] = response.attributes else authorize_failure # This method shows an error message # List of errors is available in response.errors array end end private def saml_settings settings = OneLogin::RubySaml::Settings.new settings.assertion_consumer_service_url = "http://#{request.host}/saml/consume" settings.sp_entity_id = "http://#{request.host}/saml/metadata" settings.idp_sso_service_url = "https://app.onelogin.com/saml/signon/#{OneLoginAppId}" settings.idp_cert_fingerprint = OneLoginAppCertFingerPrint settings.name_identifier_format = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress" # Optional for most SAML IdPs settings.authn_context = "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport" # Optional. Describe according to IdP specification (if supported) which attributes the SP desires to receive in SAMLResponse. settings.attributes_index = 5 # Optional. Describe an attribute consuming service for support of additional attributes. settings.attribute_consuming_service.configure do service_name "Service" service_index 5 add_attribute :name => "Name", :name_format => "Name Format", :friendly_name => "Friendly Name" end settings end end ``` -------------------------------- ### Rails Controller Example Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/logoutresponse.md A comprehensive example of a Rails controller demonstrating how to initiate a SAML logout request and handle the subsequent logout response. ```APIDOC ## Rails Controller Example ### Description This controller example shows two actions: `logout` to initiate the SAML logout process by creating a `Logoutrequest` and redirecting the user to the IdP's SLO endpoint, and `sls` (Single Logout Service) to handle the `Logoutresponse` from the IdP, validating it and managing the user's session. ### Controller Actions ```ruby class SamlController < ApplicationController def logout settings = OneLogin::RubySaml::Settings.new( sp_entity_id: 'https://app.example.com', idp_slo_service_url: 'https://idp.example.com/slo', certificate: config.certificate, security: { logout_requests_signed: true } ) logoutrequest = OneLogin::RubySaml::Logoutrequest.new settings.sessionindex = session[:saml_session_index] logout_url = logoutrequest.create(settings) session[:saml_logout_request_id] = logoutrequest.request_id # Keep other session data for now session.delete(:user_id) redirect_to logout_url end def sls settings = load_saml_settings logoutresponse = OneLogin::RubySaml::Logoutresponse.new( params[:SAMLResponse], settings, matches_request_id: session[:saml_logout_request_id] ) if logoutresponse.is_valid? && logoutresponse.success? # Clear all session session.destroy redirect_to '/', notice: 'Successfully signed out' else session.destroy redirect_to '/', alert: logoutresponse.errors.join(', ') end end end ``` ``` -------------------------------- ### Rails Controller Example for SAML Metadata Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/metadata.md A complete example of a Rails controller action to serve SAML metadata. It configures SAML settings and renders the metadata as XML. ```ruby class SamlController < ApplicationController skip_before_action :verify_authenticity_token, only: [:metadata] def metadata settings = OneLogin::RubySaml::Settings.new( sp_entity_id: 'https://app.example.com/saml/metadata', assertion_consumer_service_url: 'https://app.example.com/saml/acs', single_logout_service_url: 'https://app.example.com/saml/sls', name_identifier_format: 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress', certificate: current_app_config.saml_certificate, private_key: current_app_config.saml_private_key, security: { authn_requests_signed: true, want_assertions_signed: true, metadata_signed: false } ) metadata = OneLogin::RubySaml::Metadata.new respond_to do |format| format.xml do render xml: metadata.generate(settings) end end end end ``` -------------------------------- ### Install ruby-saml Gem with RubyGems Source: https://github.com/saml-toolkits/ruby-saml/blob/master/README.md Install the ruby-saml gem directly using the gem install command. ```sh gem install ruby-saml ``` -------------------------------- ### Rails Controller Example for SLO Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/slo_logoutrequest.md A complete example within a Rails controller demonstrating how to handle SAML Single Logout requests, including session management and response generation. ```ruby class SamlController < ApplicationController def sls settings = OneLogin::RubySaml::Settings.new( sp_entity_id: 'https://app.example.com', idp_slo_service_url: 'https://idp.example.com/slo', idp_cert: config.idp_cert, certificate: config.certificate, private_key: config.private_key, security: { logout_responses_signed: true } ) logout_req = OneLogin::RubySaml::SloLogoutrequest.new( params[:SAMLRequest], settings: settings ) if logout_req.is_valid? # Clear session name_id = logout_req.name_id session_index = logout_req.sessionindex User.update_session_cache(name_id, session_index, false) session.destroy # Send success response logout_response = OneLogin::RubySaml::SloLogoutresponse.new logout_url = logout_response.create( settings, logout_req.request_id, nil, { RelayState: params[:RelayState] } ) redirect_to logout_url else # Send error response logout_response = OneLogin::RubySaml::SloLogoutresponse.new logout_url = logout_response.create( settings, logout_req.request_id, 'Logout request invalid', { RelayState: params[:RelayState] }, 'urn:oasis:names:tc:SAML:2.0:status:Requester' ) redirect_to logout_url end end end ``` -------------------------------- ### Example - Strict Security Configuration Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/configuration.md This example demonstrates how to configure strict security settings for SAML. It enables signing for requests and responses, requires signed and encrypted assertions, signs metadata, and uses SHA256 algorithms for digest and signature methods. It also enables certificate expiration checks. ```ruby settings = OneLogin::RubySaml::Settings.new( # ... other settings ... security: { authn_requests_signed: true, logout_requests_signed: true, want_assertions_signed: true, want_assertions_encrypted: true, metadata_signed: true, digest_method: XMLSecurity::Document::SHA256, signature_method: XMLSecurity::Document::RSA_SHA256, check_idp_cert_expiration: true, check_sp_cert_expiration: true }, certificate: File.read('cert.pem'), private_key: File.read('key.pem'), idp_cert: File.read('idp_cert.pem') ) ``` -------------------------------- ### Rails Controller Example Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/slo_logoutresponse.md A comprehensive example of handling SAML Single Logout within a Rails controller, including parsing the request, validating the user, and generating the appropriate response. ```APIDOC ## Rails Controller Example This example demonstrates a typical implementation of SAML Single Logout handling within a Rails application controller. ### Controller Action ```ruby class SamlController < ApplicationController def sls settings = OneLogin::RubySaml::Settings.new( sp_entity_id: 'https://app.example.com', idp_slo_service_url: 'https://idp.example.com/slo', idp_slo_response_service_url: 'https://idp.example.com/slo-response', idp_cert: config.idp_cert, certificate: config.certificate, private_key: config.private_key, security: { logout_responses_signed: true } ) # Parse IdP logout request logout_req = OneLogin::RubySaml::SloLogoutrequest.new( params[:SAMLRequest], settings: settings ) if logout_req.is_valid? # Logout user user = User.find_by(saml_id: logout_req.name_id) if user user.update(logged_in: false) message = "User #{user.id} logged out" status_code = 'urn:oasis:names:tc:SAML:2.0:status:Success' else message = "User not found" status_code = 'urn:oasis:names:tc:SAML:2.0:status:Requester' end else message = logout_req.errors.join(', ') status_code = 'urn:oasis:names:tc:SAML:2.0:status:Requester' end # Build response logout_response = OneLogin::RubySaml::SloLogoutresponse.new logout_url = logout_response.create( settings, logout_req.request_id, message, { RelayState: params[:RelayState] }, status_code ) redirect_to logout_url end end ``` ``` -------------------------------- ### Rails Controller Example for SAML Logout Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/slo_logoutresponse.md A full example within a Rails controller demonstrating how to parse an IdP logout request, handle user logout, and generate a SAML logout response. ```ruby class SamlController < ApplicationController def sls settings = OneLogin::RubySaml::Settings.new( sp_entity_id: 'https://app.example.com', idp_slo_service_url: 'https://idp.example.com/slo', idp_slo_response_service_url: 'https://idp.example.com/slo-response', idp_cert: config.idp_cert, certificate: config.certificate, private_key: config.private_key, security: { logout_responses_signed: true } ) # Parse IdP logout request logout_req = OneLogin::RubySaml::SloLogoutrequest.new( params[:SAMLRequest], settings: settings ) if logout_req.is_valid? # Logout user user = User.find_by(saml_id: logout_req.name_id) if user user.update(logged_in: false) message = "User #{user.id} logged out" status_code = 'urn:oasis:names:tc:SAML:2.0:status:Success' else message = "User not found" status_code = 'urn:oasis:names:tc:SAML:2.0:status:Requester' end else message = logout_req.errors.join(', ') status_code = 'urn:oasis:names:tc:SAML:2.0:status:Requester' end # Build response logout_response = OneLogin::RubySaml::SloLogoutresponse.new logout_url = logout_response.create( settings, logout_req.request_id, message, { RelayState: params[:RelayState] }, status_code ) redirect_to logout_url end end ``` -------------------------------- ### Rails Controller Example Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/logoutrequest.md Provides a complete example of implementing SAML single logout within a Rails controller, covering both the logout initiation and the Single Logout Service (SLS) endpoint for response handling. ```APIDOC ## Rails Controller Example ```ruby class SamlController < ApplicationController def logout settings = OneLogin::RubySaml::Settings.new( sp_entity_id: 'https://app.example.com', idp_slo_service_url: 'https://idp.example.com/slo', assertion_consumer_service_url: 'https://app.example.com/saml/acs', single_logout_service_url: 'https://app.example.com/saml/sls', certificate: current_app_config.certificate, private_key: current_app_config.private_key, security: { logout_requests_signed: true } ) logoutrequest = OneLogin::RubySaml::Logoutrequest.new settings.sessionindex = session[:saml_session_index] logout_url = logoutrequest.create(settings, { RelayState: '/' }) session.clear redirect_to logout_url end def sls settings = load_saml_settings response = OneLogin::RubySaml::Logoutresponse.new( params[:SAMLResponse], settings: settings ) if response.is_valid? redirect_to '/', notice: 'Successfully signed out' else redirect_to '/', alert: 'Sign out failed' end end end ``` ``` -------------------------------- ### Rails Controller Example for SAML Logout Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/logoutresponse.md A comprehensive Rails controller example demonstrating how to initiate a SAML logout request and handle the subsequent logout response (SLS). It configures settings, creates a logout request URL, and processes the response. ```ruby class SamlController < ApplicationController def logout settings = OneLogin::RubySaml::Settings.new( sp_entity_id: 'https://app.example.com', idp_slo_service_url: 'https://idp.example.com/slo', certificate: config.certificate, security: { logout_requests_signed: true } ) logoutrequest = OneLogin::RubySaml::Logoutrequest.new settings.sessionindex = session[:saml_session_index] logout_url = logoutrequest.create(settings) session[:saml_logout_request_id] = logoutrequest.request_id # Keep other session data for now session.delete(:user_id) redirect_to logout_url end def sls settings = load_saml_settings logoutresponse = OneLogin::RubySaml::Logoutresponse.new( params[:SAMLResponse], settings, matches_request_id: session[:saml_logout_request_id] ) if logoutresponse.is_valid? && logoutresponse.success? # Clear all session session.destroy redirect_to '/', notice: 'Successfully signed out' else session.destroy redirect_to '/', alert: logoutresponse.errors.join(', ') end end end ``` -------------------------------- ### Rails Integration Example Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/idp_metadata_parser.md Demonstrates how to integrate IdP metadata parsing into a Rails application, dynamically loading settings based on the environment. ```APIDOC ## Rails Integration Demonstrates how to integrate IdP metadata parsing into a Rails application, dynamically loading settings based on the environment. ```ruby class SamlConfiguration def self.load_from_idp(idp_metadata_url) parser = OneLogin::RubySaml::IdpMetadataParser.new settings = parser.parse_remote( idp_metadata_url, validate_cert: !Rails.env.development?, options: { settings: { sp_entity_id: Rails.application.config.saml[:sp_entity_id], assertion_consumer_service_url: Rails.application.config.saml[:acs_url], single_logout_service_url: Rails.application.config.saml[:sls_url], certificate: File.read(Rails.application.config.saml[:certificate_path]), private_key: File.read(Rails.application.config.saml[:private_key_path]) } } ) settings.security = { authn_requests_signed: true, want_assertions_signed: true, digest_method: XMLSecurity::Document::SHA256, signature_method: XMLSecurity::Document::RSA_SHA256 } settings end end ``` ``` -------------------------------- ### Rails Controller Example for Logout Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/logoutrequest.md A complete example of a Rails controller action for initiating SAML logout. It configures SAML settings, creates a LogoutRequest, and redirects the user. It also includes a `sls` action to handle the SAML Single Logout Service response. ```ruby class SamlController < ApplicationController def logout settings = OneLogin::RubySaml::Settings.new( sp_entity_id: 'https://app.example.com', idp_slo_service_url: 'https://idp.example.com/slo', assertion_consumer_service_url: 'https://app.example.com/saml/acs', single_logout_service_url: 'https://app.example.com/saml/sls', certificate: current_app_config.certificate, private_key: current_app_config.private_key, security: { logout_requests_signed: true } ) logoutrequest = OneLogin::RubySaml::Logoutrequest.new settings.sessionindex = session[:saml_session_index] logout_url = logoutrequest.create(settings, { RelayState: '/' }) session.clear redirect_to logout_url end def sls settings = load_saml_settings response = OneLogin::RubySaml::Logoutresponse.new( params[:SAMLResponse], settings: settings ) if response.is_valid? redirect_to '/', notice: 'Successfully signed out' else redirect_to '/', alert: 'Sign out failed' end end end ``` -------------------------------- ### Clock Drift Handling Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/response.md Example of how to configure allowed clock drift when initializing the SAML response object. ```APIDOC ## Clock Drift Handling ### Description This example demonstrates how to allow for clock skew between the Identity Provider and the Service Provider by specifying `allowed_clock_drift`. ### Code Example ```ruby response = OneLogin::RubySaml::Response.new( params[:SAMLResponse], settings: settings, allowed_clock_drift: 30 ) ``` ``` -------------------------------- ### Basic SAML Response Processing Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/response.md Example of how to initialize and validate a SAML response, then process user information. ```APIDOC ## Basic SAML Response Processing ### Description This example demonstrates the typical flow for processing a SAML assertion in a web application's Assertion Consumer Service (ACS) endpoint. ### Code Example ```ruby def saml_acs settings = load_saml_settings response = OneLogin::RubySaml::Response.new( params[:SAMLResponse], settings: settings, matches_request_id: session[:saml_request_id], allowed_clock_drift: 5 ) if response.is_valid? user = find_or_create_user( name_id: response.name_id, email: response.attributes['email'], first_name: response.attributes['firstName'], last_name: response.attributes['lastName'] ) session[:user_id] = user.id session[:saml_session_index] = response.sessionindex redirect_to '/', notice: 'Signed in successfully' else redirect_to '/', alert: response.errors.join(', ') end end ``` ``` -------------------------------- ### Handle Both Bindings Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/slo_logoutresponse.md Illustrates how to handle SAML logout responses using different bindings, specifically the HTTP-Redirect (GET) binding and the HTTP-POST binding. ```APIDOC ## Handle Both Bindings This section shows how to adapt your logout response handling based on the configured SAML binding. ### Method ```ruby logout_response = OneLogin::RubySaml::SloLogoutresponse.new # Redirect binding (GET) if settings.single_logout_service_binding == 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect' logout_url = logout_response.create(settings, logout_req.request_id) redirect_to logout_url # POST binding elsif settings.single_logout_service_binding == 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST' params_hash = logout_response.create_params(settings, logout_req.request_id) # Build form for POST end ``` ``` -------------------------------- ### Full IdP Configuration Example Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/configuration.md Configure all required and several optional Identity Provider (IdP) settings, including entity ID, SSO/SLO URLs, certificate, attribute names, and binding types. Ensure the IdP certificate is read from a file. ```ruby settings = OneLogin::RubySaml::Settings.new( # Required idp_entity_id: 'urn:example:idp', idp_sso_service_url: 'https://idp.example.com/sso', idp_slo_service_url: 'https://idp.example.com/slo', idp_cert: File.read('idp_cert.pem'), # Optional idp_slo_response_service_url: 'https://idp.example.com/slo-response', idp_attribute_names: ['email', 'firstName', 'lastName'], idp_name_qualifier: 'https://idp.example.com', idp_sso_service_binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect' ) ``` -------------------------------- ### Skip SSL Verification for Development Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/idp_metadata_parser.md This example demonstrates how to skip SSL certificate verification when parsing remote metadata. WARNING: This should never be used in a production environment due to security risks. ```ruby # WARNING: Never use in production parser = OneLogin::RubySaml::IdpMetadataParser.new settings = parser.parse_remote( 'https://test-idp.example.com/metadata', validate_cert: false # Skip SSL validation ) ``` -------------------------------- ### Configure IdP and SP Settings Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/settings.md Set up SAML authentication by providing IdP and SP entity IDs, service URLs, and assertion consumer service URL. ```ruby settings = OneLogin::RubySaml::Settings.new( idp_entity_id: 'https://idp.example.com/metadata', idp_sso_service_url: 'https://idp.example.com/sso', idp_slo_service_url: 'https://idp.example.com/slo', sp_entity_id: 'https://app.example.com/saml/metadata', assertion_consumer_service_url: 'https://app.example.com/saml/acs', single_logout_service_url: 'https://app.example.com/saml/sls' ) ``` -------------------------------- ### Install Specific Nokogiri Version for Ruby 1.8.7 Source: https://github.com/saml-toolkits/ruby-saml/blob/master/README.md Install a specific version of Nokogiri compatible with Ruby 1.8.7 using the gem install command. ```sh gem install nokogiri --version '~> 1.5.10' ``` -------------------------------- ### SloLogoutresponse Class Initialization Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/slo_logoutresponse.md Initializes an empty SloLogoutresponse object with a random UUID. This is the starting point for creating logout responses. ```APIDOC ## Class: SloLogoutresponse Builds and encodes SAML logout responses. ```ruby OneLogin::RubySaml::SloLogoutresponse.new ``` ### Constructor Initializes an empty LogoutResponse with a random UUID. **Example:** ```ruby logout_response = OneLogin::RubySaml::SloLogoutresponse.new ``` ``` -------------------------------- ### Constructing SloLogoutrequest with Raw GET Parameters Source: https://github.com/saml-toolkits/ruby-saml/blob/master/UPGRADING.md Use `options[:raw_get_params]` for SAMLResponse, RelayState, and SigAlg to ensure compatibility with other SAML implementations. The old `options[:get_params]` is still supported but deprecated. ```ruby # In this example `query_params` is assumed to contain decoded query parameters, # and `raw_query_params` is assumed to contain encoded query parameters as sent by the IDP. settings = { settings.security[:signature_method] = XMLSecurity::Document::RSA_SHA1 settings.soft = false } options = { get_params: { "Signature" => query_params["Signature"], }, raw_get_params: { "SAMLRequest" => raw_query_params["SAMLRequest"], "SigAlg" => raw_query_params["SigAlg"], "RelayState" => raw_query_params["RelayState"], }, } slo_logout_request = OneLogin::RubySaml::SloLogoutrequest.new(query_params["SAMLRequest"], settings, options) raise "Invalid Logout Request" unless slo_logout_request.is_valid? ``` -------------------------------- ### Get LogoutRequest UUID Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/logoutrequest.md Instantiate a Logoutrequest object and access its `uuid` property to get the unique identifier for the request. This ID is automatically generated. ```ruby logoutrequest = OneLogin::RubySaml::Logoutrequest.new puts logoutrequest.uuid # => "_9e61671ac72bcabd5a8a449ce9c3b3f4" ``` -------------------------------- ### Configure Single Certificate and Key Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/configuration.md Set up the SP's signing certificate and private key using PEM-encoded strings. This is for basic certificate configuration. ```ruby settings = OneLogin::RubySaml::Settings.new( certificate: File.read('sp_cert.pem'), private_key: File.read('sp_key.pem') ) ``` -------------------------------- ### Get Service Provider Certificates and Keys Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/settings.md Retrieve all Service Provider certificates and private keys. Optionally filters out expired certificates if configured. ```ruby certs = settings.get_sp_certs # => { # signing: [ # [#, #], # [#, #] # ], # encryption: [...] # } ``` -------------------------------- ### Configure SP Settings Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/configuration.md Initialize SP settings with required and optional parameters. Ensure 'sp_entity_id', 'assertion_consumer_service_url', and 'single_logout_service_url' are correctly set. ```ruby settings = OneLogin::RubySaml::Settings.new( # Required sp_entity_id: 'https://app.example.com/saml/metadata', assertion_consumer_service_url: 'https://app.example.com/saml/acs', single_logout_service_url: 'https://app.example.com/saml/sls', # Optional name_identifier_format: 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress', sp_name_qualifier: 'https://app.example.com', attributes_index: 0 ) ``` -------------------------------- ### Initialize Settings with Options Hash Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/configuration.md Instantiate the Settings class by passing a hash of options. This hash will be merged with default settings. ```ruby settings = OneLogin::RubySaml::Settings.new(options_hash) ``` -------------------------------- ### Handle Multiple Metadata Sources (Dynamic or Static) Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/idp_metadata_parser.md Dynamically load SAML settings, prioritizing remote IdP metadata if a URL is provided via environment variables. Falls back to static configuration using environment variables if remote metadata is unavailable. ```ruby def load_saml_settings idp_url = ENV['SAML_IDP_METADATA_URL'] if idp_url # Auto-load from IdP metadata parser = OneLogin::RubySaml::IdpMetadataParser.new settings = parser.parse_remote( idp_url, validate_cert: Rails.env.production? ) else # Use static configuration settings = OneLogin::RubySaml::Settings.new( idp_entity_id: ENV['SAML_IDP_ENTITY_ID'], idp_sso_service_url: ENV['SAML_IDP_SSO_URL'], idp_cert: ENV['SAML_IDP_CERT'], sp_entity_id: 'https://app.example.com', assertion_consumer_service_url: 'https://app.example.com/saml/acs' ) end settings end ``` -------------------------------- ### Basic SAML Authentication in Ruby Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/README.md Demonstrates how to generate a login URL for SP-initiated authentication and validate the SAML response from the IdP. Ensure 'settings' object is properly configured. ```ruby # 1. Generate login URL authrequest = OneLogin::RubySaml::Authrequest.new login_url = authrequest.create(settings) redirect_to login_url # 2. Validate response response = OneLogin::RubySaml::Response.new( params[:SAMLResponse], settings: settings ) if response.is_valid? email = response.attributes['email'] end ``` -------------------------------- ### Example SAML Metadata XML Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/metadata.md This XML snippet shows a typical Service Provider (SP) metadata structure, including entity ID, signing certificate, logout service, and assertion consumer service endpoints. ```xml MIICajCCAdOgAwIBAgIBADANBgkqhkiG9w0BAQ... urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress ``` -------------------------------- ### Logout Response XML Structure Example Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/slo_logoutresponse.md An example of the XML structure for a SAML LogoutResponse, including essential elements like ID, InResponseTo, Version, IssueInstant, Destination, Issuer, and Status. ```xml https://app.example.com User logged out successfully ``` -------------------------------- ### Logout Request XML Structure Example Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/logoutrequest.md An example of the XML structure for a SAML LogoutRequest, including essential elements like ID, Version, IssueInstant, Destination, Issuer, NameID, and SessionIndex. ```xml https://app.example.com user@example.com 1234567890 ``` -------------------------------- ### Configure SAML Settings Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/REFERENCE.md Initialize SAML settings by providing a configuration hash. This is the first step before performing authentication or logout flows. ```ruby # 1. Configure settings settings = OneLogin::RubySaml::Settings.new(saml_config) # 2. For authentication flow, use Authrequest and Response # 3. For logout flow, use Logoutrequest and Logoutresponse # 4. Import IdP config with IdpMetadataParser # 5. Generate metadata with Metadata ``` -------------------------------- ### Example SAML AttributeStatement XML Source: https://github.com/saml-toolkits/ruby-saml/blob/master/README.md An example of a SAML `AttributeStatement` XML structure, showing various attribute types including single values, multiple values, nil values, and empty strings. ```xml demo value1 value2 role1 role2 role3 valuePresent usersName ``` -------------------------------- ### create(settings, params = {}) Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/authrequest.md Generates the complete SAML authentication request and returns a login URL for user redirection to the IdP. ```APIDOC ## Instance Methods ### create(settings, params = {}) → String Generates the complete SAML authentication request and returns a login URL to redirect the user to. | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | settings | OneLogin::RubySaml::Settings | — | SAML configuration with IdP endpoints | | params | Hash | {} | Additional query parameters (e.g., RelayState) | **Returns:** `String` — Full URL with SAMLRequest and parameters encoded **Raises:** `SettingError` if idp_sso_service_url is not configured **Example:** ```ruby settings = OneLogin::RubySaml::Settings.new( idp_sso_service_url: 'https://idp.example.com/sso', sp_entity_id: 'https://app.example.com', assertion_consumer_service_url: 'https://app.example.com/saml/acs' ) authrequest = OneLogin::RubySaml::Authrequest.new login_url = authrequest.create(settings, { RelayState: '/dashboard' }) # => "https://idp.example.com/sso?SAMLRequest=PD94bWw..." redirect_to login_url ``` ``` -------------------------------- ### Initialize SAML Settings Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/settings.md Use this snippet to configure SAML settings for both the Identity Provider (IdP) and Service Provider (SP). Ensure you provide valid certificate and key data. ```ruby settings = OneLogin::RubySaml::Settings.new( # IdP Configuration idp_entity_id: 'urn:example:idp', idp_sso_service_url: 'https://idp.example.com/sso', idp_slo_service_url: 'https://idp.example.com/slo', idp_cert: idp_cert_pem, # SP Configuration sp_entity_id: 'urn:example:sp', assertion_consumer_service_url: 'https://app.example.com/saml/acs', single_logout_service_url: 'https://app.example.com/saml/sls', # Certificates certificate: sp_cert_pem, private_key: sp_key_pem, # Security security: { authn_requests_signed: true, want_assertions_signed: true, signature_method: XMLSecurity::Document::RSA_SHA256 }, # Attributes name_identifier_format: 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress' ) ``` -------------------------------- ### Initialize Settings with Specific IdP Options Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/configuration.md Provide specific Identity Provider (IdP) configuration details, such as entity ID and SSO service URL, when initializing the Settings class. More options can be added as needed. ```ruby settings = OneLogin::RubySaml::Settings.new( idp_entity_id: 'https://idp.example.com/metadata', idp_sso_service_url: 'https://idp.example.com/sso', # ... more options ) ``` -------------------------------- ### RelayState Processing Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/response.md Explanation that RelayState is handled separately and an example of its usage. ```APIDOC ## RelayState Processing ### Description The `RelayState` parameter is not processed by the `Response` class itself; it must be handled in the controller logic, typically for redirecting the user after successful authentication. ### Code Example ```ruby def saml_acs relay_state = params[:RelayState] || '/' response = OneLogin::RubySaml::Response.new( params[:SAMLResponse], settings: settings ) if response.is_valid? redirect_to relay_state else redirect_to '/' end end ``` ``` -------------------------------- ### SAML Configuration Using Environment Variables in Ruby Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/configuration.md This pattern demonstrates how to load SAML configurations from environment variables into a hash, which can then be used to initialize the Ruby SAML settings. This approach is useful for managing sensitive information and deployment-specific settings. ```ruby # In initializer or config class SAML_CONFIG = { idp_entity_id: ENV['SAML_IDP_ENTITY_ID'], idp_sso_service_url: ENV['SAML_IDP_SSO_URL'], idp_slo_service_url: ENV['SAML_IDP_SLO_URL'], idp_cert: ENV['SAML_IDP_CERT'], sp_entity_id: ENV['SAML_SP_ENTITY_ID'], assertion_consumer_service_url: ENV['SAML_ACS_URL'], single_logout_service_url: ENV['SAML_SLS_URL'], certificate: ENV['SAML_CERTIFICATE'], private_key: ENV['SAML_PRIVATE_KEY'], security: { authn_requests_signed: ENV['SAML_SIGN_REQUESTS'] == 'true', want_assertions_signed: ENV['SAML_WANT_SIGNED_ASSERTIONS'] == 'true', digest_method: XMLSecurity::Document::SHA256, signature_method: XMLSecurity::Document::RSA_SHA256 } } # Load settings settings = OneLogin::RubySaml::Settings.new(SAML_CONFIG) ``` -------------------------------- ### Get Logout Response ID Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/logoutresponse.md Retrieves the unique identifier for the logout response. ```ruby response_id = logoutresponse.response_id ``` -------------------------------- ### Initialize Settings Object Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/settings.md Instantiate the Settings class with optional overrides and a flag to control security attribute merging. ```ruby OneLogin::RubySaml::Settings.new(overrides = {}, keep_security_attributes = false) ``` -------------------------------- ### Get Session Index for Logout Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/slo_logoutrequest.md Retrieve the SessionIndex associated with the logout request. ```ruby session_index = logout_req.sessionindex ``` -------------------------------- ### Initialize SAML Response with Options Source: https://github.com/saml-toolkits/ruby-saml/blob/master/README.md Demonstrates initializing a SAML response object with various options to skip specific checks like AuthnStatement, conditions, subject confirmation, recipient check, or audience. ```ruby response = OneLogin::RubySaml::Response.new(params[:SAMLResponse], {skip_authnstatement: true}) # skips AuthnStatement ``` ```ruby response = OneLogin::RubySaml::Response.new(params[:SAMLResponse], {skip_conditions: true}) # skips conditions ``` ```ruby response = OneLogin::RubySaml::Response.new(params[:SAMLResponse], {skip_subject_confirmation: true}) # skips subject confirmation ``` ```ruby response = OneLogin::RubySaml::Response.new(params[:SAMLResponse], {skip_recipient_check: true}) # doesn't skip subject confirmation, but skips the recipient check which is a sub check of the subject_confirmation check ``` ```ruby response = OneLogin::RubySaml::Response.new(params[:SAMLResponse], {skip_audience: true}) # skips audience check ``` -------------------------------- ### Get Logout Request ID Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/slo_logoutrequest.md Retrieve the unique identifier for the logout request. ```ruby request_id = logout_req.request_id ``` -------------------------------- ### Get SAML Response ID Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/response.md Retrieves the unique identifier for the SAML response message. ```ruby response_id = response.response_id ``` -------------------------------- ### SP-Initiated Authentication Workflow Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/README.md Illustrates the steps for initiating authentication from the Service Provider (SP) side, involving settings, creating an Authrequest, redirecting to the Identity Provider (IdP), and validating the SAMLResponse. ```text Settings → Authrequest.create() → Redirect to IdP IdP sends SAMLResponse → Response.is_valid() → User logged in ``` -------------------------------- ### Get NameID Format Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/slo_logoutrequest.md Retrieve the format of the user's NameID. This is an alias for `nameid_format()`. ```ruby format = logout_req.name_id_format ``` -------------------------------- ### Instantiate SloLogoutrequest Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/slo_logoutrequest.md Instantiate the SloLogoutrequest class with the SAML request string and optional settings. The options hash can include SAML settings, allowed clock drift, and signature validation relaxation. ```ruby OneLogin::RubySaml::SloLogoutrequest.new(request, options = {}) ``` -------------------------------- ### Get Multiple IdP Certificates Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/settings.md Retrieves multiple Identity Provider certificates, organized by type. ```APIDOC ## Get Multiple IdP Certificates ### Description Get multiple IdP certificates organized by type. ### Method `settings.get_idp_cert_multi()` ### Returns - `Hash` - A hash containing certificates organized by type (e.g., `signing`, `encryption`). ### Request Example ```ruby certs = settings.get_idp_cert_multi # => { signing: [...], encryption: [...] } ``` ``` -------------------------------- ### Load SAML Configuration from Files Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/configuration.md Loads SAML configuration, including certificates and private keys, from specified file paths. This is useful for managing sensitive credentials securely on the server. ```ruby # Store certificates in files settings = OneLogin::RubySaml::Settings.new( idp_cert: File.read('config/saml/idp.crt'), certificate: File.read('config/saml/sp.crt'), private_key: File.read('config/saml/sp.key') ) ``` -------------------------------- ### Get IdP Certificate Object Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/settings.md Builds and returns the Identity Provider's certificate object. ```APIDOC ## Get IdP Certificate Object ### Description Build and return the IdP certificate object. ### Method `settings.get_idp_cert()` ### Returns - `OpenSSL::X509::Certificate|nil` - The IdP certificate object or nil if not available. ### Request Example ```ruby cert = settings.get_idp_cert # => # ``` ``` -------------------------------- ### Basic Remote Metadata Import Source: https://github.com/saml-toolkits/ruby-saml/blob/master/_autodocs/api-reference/idp_metadata_parser.md Import IdP metadata from a remote URL and configure basic Service Provider settings. Ensure the certificate is validated for security. ```ruby parser = OneLogin::RubySaml::IdpMetadataParser.new settings = parser.parse_remote( 'https://idp.example.com/metadata', validate_cert: true ) # Add SP-specific settings settings.sp_entity_id = 'https://app.example.com' settings.assertion_consumer_service_url = 'https://app.example.com/saml/acs' settings.single_logout_service_url = 'https://app.example.com/saml/sls' ```