JIT Handler to get a subject value from a SAML Assertion

PHOTO EMBED

Thu Nov 02 2023 13:19:30 GMT+0000 (Coordinated Universal Time)

Saved by @Justus #apex

global class JitHandlerExample  implements Auth.SamlJitHandler {
    
    // Do nothing on create
    global User createUser(Id samlSsoProviderId, Id communityId, Id portalId, String federationIdentifier, Map<String, String> attributes, String assertion){
        return null;
    }

    // On update
    global void updateUser(Id userId, Id samlSsoProviderId, Id communityId, Id portalId, String federationIdentifier, Map<String, String> attributes, String assertion) {
        
      	// For Encrypted assertions use
      	// assertion = attributes.get('Sfdc.SamlAssertion')
      
        // Get the subject
        String subject = getSubjectFromAssertion(EncodingUtil.Base64Decode(assertion).toString());
        
        // Do whatever you need to do with the subject
        lwt.Dbg.al(subject);
        lwt.Dbg.pub();
    }


    /**
     * @description Method to get the subject from the assertion
     */
    private String getSubjectFromAssertion(String decodedAssertion){
        
        XmlStreamReader reader = new XmlStreamReader(decodedAssertion);
    
        boolean isSafeToGetNextXmlElement = true;
        while(isSafeToGetNextXmlElement) {
            if (reader.getEventType() == XmlTag.START_ELEMENT) {
                
                // Find the nameId element
                if (reader.getLocalName() == 'NameID') {
                    
                    // Go to the text part of the element (part after the start tag)
                    reader.next();
                    
                    // Return the value of the element
                    return reader.getText();
                }
            }
    
            if (reader.hasNext()) {
                reader.next();
            }else{
                isSafeToGetNextXmlElement = false;
                break;
            }
        }
        return null;
    }
}
content_copyCOPY