### Install Java SAML Toolkit via Maven Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md To integrate the OneLogin Java SAML toolkit into your project, add this dependency to your pom.xml file. This will automatically download the library from the Central Repository. ```XML com.onelogin java-saml 2.9.0 ``` -------------------------------- ### Instantiate OneLogin SAML Auth with Dynamic Settings Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md Provides a concise example of how to instantiate the 'Auth' class using a 'Saml2Settings' object that has been configured dynamically. This instantiation typically requires the 'settings' object along with 'HttpServletRequest' and 'HttpServletResponse' objects for context. ```java Auth auth = new Auth(settings, request, response); ``` -------------------------------- ### Initiate SAML SSO Login with RelayState in Java Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md This example shows how to include a 'RelayState' parameter when initiating a SAML SSO login. The RelayState typically contains a return URL that the user will be redirected to after successful authentication at the IdP. ```java String returnUrl = 'https://example.com'; auth.login(relayState=returnUrl) ``` -------------------------------- ### Initiate SAML SLO with RelayState in Java Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md This example shows how to include a `RelayState` parameter, typically a return URL, when initiating a SAML Logout Request. The `RelayState` can be used to redirect the user to a specific page after the logout process is complete. ```java String returnUrl = 'https://example.com'; auth.logout(relayState=returnUrl) ``` -------------------------------- ### Example Structure of SAML User Attributes Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md This JSON snippet illustrates the typical structure of user attributes returned by the `getAttributes()` method. Each attribute name (e.g., 'cn', 'sn', 'mail', 'groups') maps to a list of string values. Even single-valued attributes are represented as a list containing one element. ```JSON { "cn": ["Jhon"], "sn": ["Doe"], "mail": ["Doe"], "groups": ["users", "members"] } ``` -------------------------------- ### Extend SAML Message Factory for Custom Behavior in Java Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md This example demonstrates how to extend the `SamlMessageFactory` to use custom `AuthnRequest` and `SamlResponse` classes. This allows developers to override the `postProcessXml` method and customize the generation of SAML message XML or modify validation behavior. ```java Auth auth = new Auth(request, response); auth.setSamlMessageFactory(new SamlMessageFactory() { @Override public AuthnRequest createAuthnRequest(Saml2Settings settings, AuthnRequestParams params) { return new AuthnRequestEx(settings, (AuthnRequestParamsEx) params); } @Override public SamlResponse createSamlResponse(Saml2Settings settings, HttpRequest request) throws Exception { return new SamlResponseEx(settings, request); } }); // then proceed with login... auth.login(relayState, new AuthnRequestParamsEx()); // the custom generation of AuthnReqeustEx will be executed // ... or process the response as usual auth.processResponse(); // the custom validation of SamlResponseEx will be executed ``` -------------------------------- ### Auth Object: Get Last Processed SAML Message ID Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md The `Auth` object provides a method to retrieve the ID of the last SAML message processed by the toolkit. This ID is crucial for implementing replay attack prevention by allowing applications to store and check against previously processed message IDs. Messages expire, so long-term storage is not required beyond the accepted timeframe. ```APIDOC Class: Auth Method: getLastMessageId() Description: Retrieves the ID of the last processed SAML message. Return Type: string (SAML message ID) ``` -------------------------------- ### Initialize OneLogin SAML Auth with Java KeyStore Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md Demonstrates how to initialize the 'Auth' class in the OneLogin Java SAML toolkit by loading SP public certificates and private keys from a Java KeyStore. This approach requires providing a 'KeyStoreSettings' object, which encapsulates the KeyStore instance, the alias for the desired key entry, and its corresponding password. ```java import java.io.FileInputStream; import java.security.KeyStore; import com.onelogin.saml2.Auth; import com.onelogin.saml2.model.KeyStoreSettings; String keyStoreFile = "oneloginTestKeystore.jks"; String alias = "keywithpassword"; String storePass = "changeit"; String keyPassword = "keypassword"; KeyStore ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream(keyStoreFile), storePass.toCharArray()); KeyStoreSettings keyStoreSettings = new KeyStoreSettings(ks, alias, keyPassword); Auth auth = new Auth(keyStoreSettings); ``` -------------------------------- ### Dynamically Configure OneLogin SAML Settings in Java Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md Illustrates how to programmatically build SAML settings using the 'SettingsBuilder' class and a 'Map'. This method allows for flexible configuration by loading values from various sources such as files, databases, or dynamically generated data, providing an alternative to static property files. ```java Map samlData = new HashMap<>(); samlData.put("onelogin.saml2.sp.entityid", "http://localhost:8080/java-saml-tookit-jspsample/metadata.jsp"); samlData.put("onelogin.saml2.sp.assertion_consumer_service.url", new URL("http://localhost:8080/java-saml-tookit-jspsample/acs.jsp")); samlData.put("onelogin.saml2.security.want_xml_validation",true); samlData.put("onelogin.saml2.sp.x509cert", myX509CertInstance); SettingsBuilder builder = new SettingsBuilder(); Saml2Settings settings = builder.fromValues(samlData).build(); ``` -------------------------------- ### Configure SP Organization Details Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md Sets the organizational details for the Service Provider, including its name, display name, URL, and language. This information is typically included in the SP's metadata. ```APIDOC onelogin.saml2.organization.name = SP Java onelogin.saml2.organization.displayname = SP Java Example onelogin.saml2.organization.url = http://sp.example.com onelogin.saml2.organization.lang = en ``` -------------------------------- ### Configure SP Certificates and Private Key Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md Defines the Service Provider's X.509 certificates for signing and encryption, including a future certificate for key rollover, and the associated private key. The private key must be in PKCS#8 format. ```APIDOC onelogin.saml2.sp.x509cert = # Future SP certificate, to be used during SP Key roll over onelogin.saml2.sp.x509certNew = # Requires Format PKCS#8 BEGIN PRIVATE KEY # If you have PKCS#1 BEGIN RSA PRIVATE KEY convert it by openssl pkcs8 -topk8 -inform pem -nocrypt -in sp.rsa_key -outform pem -out sp.pem onelogin.saml2.sp.privatekey = ``` -------------------------------- ### Initiate SAML SSO Login in Java Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md This snippet demonstrates how to initiate a SAML Single Sign-On (SSO) process by creating an Auth object with HttpServletRequest and HttpServletResponse and then calling the login method. This sends an AuthNRequest to the Identity Provider (IdP). ```java Auth auth = new Auth(request, response); auth.login(); ``` -------------------------------- ### Auth.login() Method Optional Parameters Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md This section details the optional parameters available for the `Auth.login()` method, allowing for fine-grained control over the generated AuthNRequest and the redirection behavior. It includes parameters for forcing authentication, passive authentication, NameID policy, and custom parameters. ```APIDOC Auth.login(authnRequestParams: object, stay: boolean, parameters: object) authnRequestParams: object forceAuthn: boolean (When true the AuthNRequest will have the `ForceAuthn` attribute set to `true`) isPassive: boolean (When true the AuthNRequest will have the `IsPassive` attribute set to `true`) setNameIdPolicy: boolean (When true the AuthNRequest will set a `NameIdPolicy` element) allowCreate: boolean (When true, and *setNameIdPolicy* is also true, the AuthNRequest will have the `AllowCreate` attribute set to `true` on the `NameIdPolicy` element) nameIdValueReq: string (Indicates to the IdP the subject that should be authenticated) stay: boolean (Set to true to stay (returns the url string), otherwise set to false to execute a redirection to that url (IdP SSO URL)) parameters: object (Use it to send extra parameters in addition to the AuthNRequest) ``` -------------------------------- ### Generate and Validate SAML SP Metadata in Java Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md This snippet demonstrates how to generate the Service Provider (SP) metadata XML using the `java-saml` toolkit. It retrieves settings, generates the metadata string, validates it, and then prints the metadata or any validation errors to the output. ```java Auth auth = new Auth(); Saml2Settings settings = auth.getSettings(); String metadata = settings.getSPMetadata(); List errors = Saml2Settings.validateMetadata(metadata); if (errors.isEmpty()) { out.println(metadata); } else { response.setContentType("text/html; charset=UTF-8"); for (String error : errors) { out.println("

"+error+"

"); } } ``` -------------------------------- ### Configure SP Contact Information Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md Specifies various contact persons for the Service Provider, such as administrative, technical, and support contacts. Multiple contacts, email addresses, and phone numbers can be defined using indexed properties. Legacy contact fields are also supported. ```APIDOC onelogin.saml2.sp.contact[0].contactType=administrative onelogin.saml2.sp.contact[0].company=ACME onelogin.saml2.sp.contact[0].given_name=Guy onelogin.saml2.sp.contact[0].sur_name=Administrative onelogin.saml2.sp.contact[0].email_address[0]=administrative@example.com onelogin.saml2.sp.contact[0].email_address[1]=administrative2@example.com onelogin.saml2.sp.contact[0].telephone_number[0]=+1-123456789 onelogin.saml2.sp.contact[0].telephone_number[1]=+1-987654321 onelogin.saml2.sp.contact[1].contactType=other onelogin.saml2.sp.contact[1].company=Big Corp onelogin.saml2.sp.contact[1].email_address=info@example.com # Legacy contacts (legacy way to specify just a technical and a support contact with minimal info) onelogin.saml2.contacts.technical.given_name = Technical Guy onelogin.saml2.contacts.technical.email_address = technical@example.com onelogin.saml2.contacts.support.given_name = Support Guy onelogin.saml2.contacts.support.email_address = support@example.com ``` -------------------------------- ### Optional Parameters for `auth.logout()` Method Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md Describes the optional parameters that can be passed to the `auth.logout()` method to customize the Single Logout process, including details for `logoutRequestParams`, `stay`, and `parameters`. ```APIDOC auth.logout( relayState: string, logoutRequestParams: object, stay: boolean, parameters: object ) Parameters: relayState: string (optional) Description: A return URL to the login function. logoutRequestParams: object (optional) Description: Allows shaping the LogoutRequest with specific properties. Properties: sessionIndex: string Description: Identifies the session of the user. nameId: string Description: Used to build the LogoutRequest. If not set, the NameID from a processed SAML Response is used. nameidFormat: string Description: The NameID Format that will be set on the LogoutRequest. nameIdNameQualifier: string Description: The NameID NameQualifier that will be set on the LogoutRequest. nameIdSPNameQualifier: string Description: The NameID SPNameQualifier that will be set on the LogoutRequest. stay: boolean (optional) Description: If true, returns the URL string; if false, executes a redirection to the IdP SLS URL. parameters: object (optional) Description: Used to send extra parameters in addition to the LogoutRequest. ``` -------------------------------- ### Initiate SAML Single Logout (SLO) in Java Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md This snippet demonstrates how to initiate a SAML Logout Request to an IdP using the `Auth` object. It shows how to retrieve and pass `nameId`, `nameIdFormat`, `nameidNameQualifier`, `nameidSPNameQualifier`, and `sessionIndex` from the user's session to construct the `LogoutRequestParams`. ```java Auth auth = new Auth(request, response); String nameId = null; if (session.getAttribute("nameId") != null) { nameId = session.getAttribute("nameId").toString(); } String nameIdFormat = null; if (session.getAttribute("nameIdFormat") != null) { nameIdFormat = session.getAttribute("nameIdFormat").toString(); } String nameidNameQualifier = null; if (session.getAttribute("nameidNameQualifier") != null) { nameIdFormat = session.getAttribute("nameidNameQualifier").toString(); } String nameidSPNameQualifier = null; if (session.getAttribute("nameidSPNameQualifier") != null) { nameidSPNameQualifier = session.getAttribute("nameidSPNameQualifier").toString(); } String sessionIndex = null; if (session.getAttribute("sessionIndex") != null) { sessionIndex = session.getAttribute("sessionIndex").toString(); } auth.logout(null, new LogoutRequestParams(sessionIndex, nameId, nameIdFormat)); ``` -------------------------------- ### SAML Toolkit Configuration Properties Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md This properties file defines the core SAML settings for the Service Provider (SP) and Identity Provider (IdP). It includes parameters for strict mode, debug mode, SP entity ID, Assertion Consumer Service (ACS) URL and binding, Single Logout Service (SLS) URL and binding, and the NameID format. These settings are crucial for the SAML authentication and logout flows. ```Properties # If 'strict' is True, then the Java Toolkit will reject unsigned # or unencrypted messages if it expects them signed or encrypted # Also will reject the messages if not strictly follow the SAML onelogin.saml2.strict = false # Enable debug mode (to print errors) onelogin.saml2.debug = false ## Service Provider Data that we are deploying ## # Identifier of the SP entity (must be a URI) onelogin.saml2.sp.entityid = http://localhost:8080/java-saml-tookit-jspsample/metadata.jsp # Specifies info about where and how the message MUST be # returned to the requester, in this case our SP. # URL Location where the from the IdP will be returned onelogin.saml2.sp.assertion_consumer_service.url = http://localhost:8080/java-saml-tookit-jspsample/acs.jsp # SAML protocol binding to be used when returning the # message. SAMLToolkit supports for this endpoint the # HTTP-POST binding only onelogin.saml2.sp.assertion_consumer_service.binding = urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST # Specifies info about where and how the message MUST be # returned to the requester, in this case our SP. onelogin.saml2.sp.single_logout_service.url = http://localhost:8080/java-saml-tookit-jspsample/sls.jsp # SAML protocol binding to be used when returning the or sending the # message. SAMLToolkit supports for this endpoint the # HTTP-Redirect binding only onelogin.saml2.sp.single_logout_service.binding = urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect # Specifies constraints on the name identifier to be used to # represent the requested subject. # Take a look on core/src/main/java/com/onelogin/saml2/util/Constants.java to see the NameIdFormat supported onelogin.saml2.sp.nameidformat = urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified # Usually x509cert and privateKey of the SP are provided by files placed at ``` -------------------------------- ### Configure SAML Security and Parsing Properties for Java SP Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md This section defines various SAML 2.0 security and parsing related configuration properties for a Service Provider (SP) using the OneLogin Java SAML toolkit. It covers requirements for assertion signing/encryption, metadata signing, authentication context, XML validation, allowed signature and digest algorithms, and options for NameID and attribute value trimming. ```properties onelogin.saml2.security.want_assertions_signed = false onelogin.saml2.security.sign_metadata = onelogin.saml2.security.want_assertions_encrypted = false onelogin.saml2.security.want_nameid_encrypted = false onelogin.saml2.security.requested_authncontext = urn:oasis:names:tc:SAML:2.0:ac:classes:Password onelogin.saml2.security.requested_authncontextcomparison = exact onelogin.saml2.security.allow_duplicated_attribute_name = false onelogin.saml2.security.want_xml_validation = true onelogin.saml2.security.signature_algorithm = http://www.w3.org/2001/04/xmldsig-more#rsa-sha256 onelogin.saml2.security.digest_algorithm = http://www.w3.org/2001/04/xmlenc#sha256 onelogin.saml2.security.reject_deprecated_alg = true onelogin.saml2.parsing.trim_name_ids = false onelogin.saml2.parsing.trim_attribute_values = false # onelogin.saml2.unique_id_prefix = _ ``` -------------------------------- ### Configure SAML Security Settings Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md Defines various security-related settings for SAML interactions, including whether NameID, AuthnRequest, LogoutRequest, and LogoutResponse messages sent by the SP should be encrypted or signed. It also specifies if incoming messages from the IdP are required to be signed. ```APIDOC # Security settings # # Indicates that the nameID of the sent by this SP # will be encrypted. onelogin.saml2.security.nameid_encrypted = false # Indicates whether the messages sent by this SP # will be signed. [The Metadata of the SP will offer this info] onelogin.saml2.security.authnrequest_signed = false # Indicates whether the messages sent by this SP # will be signed. onelogin.saml2.security.logoutrequest_signed = false # Indicates whether the messages sent by this SP # will be signed. onelogin.saml2.security.logoutresponse_signed = false # Indicates a requirement for the , and # elements received by this SP to be signed. onelogin.saml2.security.want_messages_signed = false ``` -------------------------------- ### Configure IdP Entity and Single Sign-On (SSO) Endpoint Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md Defines the Identity Provider's entity ID and the URL for its Single Sign-On service. This is where the Service Provider sends authentication requests. The binding for the AuthnRequest message is typically HTTP-Redirect. ```APIDOC # Identifier of the IdP entity (must be a URI) onelogin.saml2.idp.entityid = # SSO endpoint info of the IdP. (Authentication Request protocol) # URL Target of the IdP where the SP will send the Authentication Request Message onelogin.saml2.idp.single_sign_on_service.url = # SAML protocol binding to be used to deliver the message # to the IdP. SAMLToolkit supports for this endpoint the # HTTP-Redirect binding only onelogin.saml2.idp.single_sign_on_service.binding = urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect ``` -------------------------------- ### Configure IdP Single Logout (SLO) Endpoints Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md Specifies the Identity Provider's Single Logout service URLs, including the endpoint for sending SLO requests and an optional separate URL for SLO responses. The binding for SLO messages is typically HTTP-Redirect. ```APIDOC # SLO endpoint info of the IdP. # URL Location of the IdP where the SP will send the SLO Request onelogin.saml2.idp.single_logout_service.url = # Optional SLO Response endpoint info of the IdP. # URL Location of the IdP where the SP will send the SLO Response. If left blank, same URL as onelogin.saml2.idp.single_logout_service.url will be used. # Some IdPs use a separate URL for sending a logout request and response, use this property to set the separate response url onelogin.saml2.idp.single_logout_service.response.url = # SAML protocol binding to be used when returning the # message. SAMLToolkit supports for this endpoint the # HTTP-Redirect binding only onelogin.saml2.idp.single_logout_service.binding = urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect ``` -------------------------------- ### Handle SAML Single Logout (SLO) in Java Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md This Java code snippet demonstrates how to implement the Single Logout Service (SLS) endpoint. It processes both incoming Logout Requests and Logout Responses using `auth.processSLO()`. The code checks for errors and provides feedback. It also notes that the `processSLO` method can invalidate the local session, with an option to prevent this using the `keepLocalSession` parameter. ```Java Auth auth = new Auth(request, response); auth.processSLO(); List errors = auth.getErrors(); if (errors.isEmpty()) { out.println("Sucessfully logged out"); } else { for(String error : errors) { out.println(error); } } ``` -------------------------------- ### Retrieve User Attributes from SAML Response in Java Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md This snippet shows the method call to retrieve user attributes from the processed SAML response. The `getAttributes()` method returns a Map where keys are attribute names and values are lists of strings. It's crucial to ensure the user is authenticated before calling this method, otherwise an empty Map will be returned. ```Java Map> attributes = auth.getAttributes(); ``` -------------------------------- ### Process SAML Response in Java Attribute Consumer Service (ACS) Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md This Java code snippet demonstrates how to handle an incoming SAML response from an Identity Provider (IdP) at the Service Provider's (SP) Attribute Consumer Service (ACS). It processes the response using the `Auth` object, checks for authentication status and errors, and then extracts and stores user attributes (NameID, session index, etc.) in the session. It also includes logic for redirection based on the `RelayState` parameter or displaying attributes directly if no `RelayState` is provided. ```Java Auth auth = new Auth(request, response); auth.processResponse(); if (!auth.isAuthenticated()) { out.println("Not authenticated"); } List errors = auth.getErrors(); if (!errors.isEmpty()) { out.println(StringUtils.join(errors, ", ")); if (auth.isDebugActive()) { String errorReason = auth.getLastErrorReason(); if (errorReason != null && !errorReason.isEmpty()) { out.println(auth.getLastErrorReason()); } } } else { Map> attributes = auth.getAttributes(); String nameId = auth.getNameId(); String nameIdFormat = auth.getNameIdFormat(); String sessionIndex = auth.getSessionIndex(); String nameidNameQualifier = auth.getNameIdNameQualifier(); String nameidSPNameQualifier = auth.getNameIdSPNameQualifier(); session.setAttribute("attributes", attributes); session.setAttribute("nameId", nameId); session.setAttribute("nameIdFormat", nameIdFormat); session.setAttribute("sessionIndex", sessionIndex); session.setAttribute("nameidNameQualifier", nameidNameQualifier); session.setAttribute("nameidSPNameQualifier", nameidSPNameQualifier); String relayState = request.getParameter("RelayState"); if (relayState != null && relayState != ServletUtils.getSelfRoutedURLNoQuery(request)) { response.sendRedirect(request.getParameter("RelayState")); } else { if (attributes.isEmpty()) { out.println("You don't have any attributes"); } else { Collection keys = attributes.keySet(); for(String name :keys){ out.println(name); List values = attributes.get(name); for(String value :values) { out.println(" - " + value); } } } } } ``` -------------------------------- ### Configure IdP Certificate and Fingerprint Validation Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md Sets the Identity Provider's public X.509 certificate for validating SAML messages. Optionally, a certificate fingerprint can be used for SAMLResponse validation, but it is not recommended for production due to collision risks. If a fingerprint is used, its algorithm must be specified. ```APIDOC # Public x509 certificate of the IdP onelogin.saml2.idp.x509cert = # Instead of using the whole x509cert you can use a fingerprint in order to # validate a SAMLResponse (but you still need the x509cert to validate LogoutRequest and LogoutResponse using the HTTP-Redirect binding). # But take in mind that the fingerprint, is a hash, so at the end is open to a collision attack that can end on a signature validation bypass, # that why we don't recommend it use for production environments. # (openssl x509 -noout -fingerprint -in "idp.crt" to generate it, # or add for example the -sha256 , -sha384 or -sha512 parameter) # # If a fingerprint is provided, then the certFingerprintAlgorithm is required in order to # let the toolkit know which Algorithm was used. Possible values: sha1, sha256, sha384 or sha512 # 'sha1' is the default value. # onelogin.saml2.idp.certfingerprint = # onelogin.saml2.idp.certfingerprint_algorithm = sha256 ``` -------------------------------- ### Retrieve Last SAML Request ID in Java Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md This snippet demonstrates how to retrieve the ID of the last SAML request sent. This is particularly useful when the `stay` parameter is set to `true` in the `logout` method, allowing for manual redirection and subsequent validation of the Logout Response against the stored request ID. ```java auth.getLastRequestId() ``` -------------------------------- ### Retrieve Last AuthNRequest ID in Java Source: https://github.com/saml-toolkits/java-saml/blob/master/README.md When the `Auth.login()` method is called with `stay` set to true, this snippet shows how to retrieve the ID of the last generated AuthNRequest. This ID is crucial for future validation against the SAMLResponse ID, allowing for manual redirection. ```java auth.getLastRequestId() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.