userService = UserService.instance() authenticationService = AuthenticationService.instance() foundUser = userService.getUserByAttribute("oxExternalUid", self.getUserValueFromAuth("provider", requestParameters) + ":" + self.getUserValueFromAuth( self.getUidRemoteAttr(), requestParameters)) if (foundUser == None): newUser = User() try: UserEmail = self.getUserValueFromAuth("email", requestParameters) except Exception, err: print("Passport: Error in getting user email: " + str(err)) if (StringHelper.isEmptyString(UserEmail)): facesMessages = FacesMessages.instance() FacesContext.getCurrentInstance().getExternalContext().getFlash().setKeepMessages(True) facesMessages.clear() facesMessages.add(StatusMessage.Severity.ERROR, "Please provide your email.") print "Passport: Email was not received so sent error" return False for attributesMappingEntry in self.attributesMapping.entrySet(): remoteAttribute = attributesMappingEntry.getKey() localAttribute = attributesMappingEntry.getValue() localAttributeValue = self.getUserValueFromAuth(remoteAttribute, requestParameters) if ((localAttribute != None) & (localAttributeValue != "undefined") & ( localAttribute != "provider")): newUser.setAttribute(localAttribute, localAttributeValue) newUser.setAttribute("oxExternalUid", self.getUserValueFromAuth("provider",
def authenticate(self, configurationAttributes, requestParameters, step): context = Contexts.getEventContext() authenticationService = AuthenticationService.instance() userService = UserService.instance() saml_map_user = False saml_enroll_user = False saml_enroll_all_user_attr = False # Use saml_deployment_type only if there is no attributes mapping if (configurationAttributes.containsKey("saml_deployment_type")): saml_deployment_type = StringHelper.toLowerCase( configurationAttributes.get( "saml_deployment_type").getValue2()) if (StringHelper.equalsIgnoreCase(saml_deployment_type, "map")): saml_map_user = True if (StringHelper.equalsIgnoreCase(saml_deployment_type, "enroll")): saml_enroll_user = True if (StringHelper.equalsIgnoreCase(saml_deployment_type, "enroll_all_attr")): saml_enroll_all_user_attr = True saml_allow_basic_login = False if (configurationAttributes.containsKey("saml_allow_basic_login")): saml_allow_basic_login = StringHelper.toBoolean( configurationAttributes.get( "saml_allow_basic_login").getValue2(), False) use_basic_auth = False if (saml_allow_basic_login): # Detect if user used basic authnetication method credentials = Identity.instance().getCredentials() user_name = credentials.getUsername() user_password = credentials.getPassword() if (StringHelper.isNotEmpty(user_name) and StringHelper.isNotEmpty(user_password)): use_basic_auth = True if ((step == 1) and saml_allow_basic_login and use_basic_auth): print "Saml. Authenticate for step 1. Basic authentication" context.set("saml_count_login_steps", 1) credentials = Identity.instance().getCredentials() user_name = credentials.getUsername() user_password = credentials.getPassword() logged_in = False if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)): userService = UserService.instance() logged_in = userService.authenticate(user_name, user_password) if (not logged_in): return False return True if (step == 1): print "Saml. Authenticate for step 1" currentSamlConfiguration = self.getCurrentSamlConfiguration( self.samlConfiguration, configurationAttributes, requestParameters) if (currentSamlConfiguration == None): print "Saml. Prepare for step 1. Client saml configuration is invalid" return False saml_response_array = requestParameters.get("SAMLResponse") if ArrayHelper.isEmpty(saml_response_array): print "Saml. Authenticate for step 1. saml_response is empty" return False saml_response = saml_response_array[0] print "Saml. Authenticate for step 1. saml_response: '%s'" % saml_response samlResponse = Response(currentSamlConfiguration) samlResponse.loadXmlFromBase64(saml_response) saml_validate_response = True if (configurationAttributes.containsKey("saml_validate_response")): saml_validate_response = StringHelper.toBoolean( configurationAttributes.get( "saml_validate_response").getValue2(), False) if (saml_validate_response): if (not samlResponse.isValid()): print "Saml. Authenticate for step 1. saml_response isn't valid" saml_response_attributes = samlResponse.getAttributes() print "Saml. Authenticate for step 1. attributes: '%s'" % saml_response_attributes if (saml_map_user): saml_user_uid = self.getSamlNameId(samlResponse) if saml_user_uid == None: return False # Use mapping to local IDP user print "Saml. Authenticate for step 1. Attempting to find user by oxExternalUid: saml: '%s'" % saml_user_uid # Check if the is user with specified saml_user_uid find_user_by_uid = userService.getUserByAttribute( "oxExternalUid", "saml:%s" % saml_user_uid) if (find_user_by_uid == None): print "Saml. Authenticate for step 1. Failed to find user" print "Saml. Authenticate for step 1. Setting count steps to 2" context.set("saml_count_login_steps", 2) context.set("saml_user_uid", saml_user_uid) return True found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 1. found_user_name: '%s'" % found_user_name user_authenticated = authenticationService.authenticate( found_user_name) if (user_authenticated == False): print "Saml. Authenticate for step 1. Failed to authenticate user" return False print "Saml. Authenticate for step 1. Setting count steps to 1" context.set("saml_count_login_steps", 1) post_login_result = self.samlExtensionPostLogin( configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 1. post_login_result: '%s'" % post_login_result return post_login_result elif (saml_enroll_user): # Convert SAML response to user entry newUser = self.getMappedUser(configurationAttributes, requestParameters, saml_response_attributes) saml_user_uid = self.getNameId(samlResponse, newUser) if saml_user_uid == None: return False self.setDefaultUid(newUser, saml_user_uid) newUser.setAttribute("oxExternalUid", "saml:%s" % saml_user_uid) # Use auto enrollment to local IDP print "Saml. Authenticate for step 1. Attempting to find user by oxExternalUid: saml: '%s'" % saml_user_uid # Check if there is user with specified saml_user_uid find_user_by_uid = userService.getUserByAttribute( "oxExternalUid", "saml:%s" % saml_user_uid) if find_user_by_uid == None: # Auto user enrollment print "Saml. Authenticate for step 1. There is no user in LDAP. Adding user to local LDAP" print "Saml. Authenticate for step 1. Attempting to add user '%s' with next attributes: '%s'" % ( saml_user_uid, newUser.getCustomAttributes()) user_unique = self.checkUserUniqueness(newUser) if not user_unique: print "Saml. Authenticate for step 1. Failed to add user: '******'. User not unique" % newUser.getUserId( ) facesMessages = FacesMessages.instance() facesMessages.add( StatusMessage.Severity.ERROR, "Failed to enroll. User with same key attributes exist already" ) FacesContext.getCurrentInstance().getExternalContext( ).getFlash().setKeepMessages(True) return False find_user_by_uid = userService.addUser(newUser, True) print "Saml. Authenticate for step 1. Added new user with UID: '%s'" % find_user_by_uid.getUserId( ) else: if self.updateUser: print "Saml. Authenticate for step 1. Attempting to update user '%s' with next attributes: '%s'" % ( saml_user_uid, newUser.getCustomAttributes()) find_user_by_uid.setCustomAttributes( newUser.getCustomAttributes()) userService.updateUser(find_user_by_uid) print "Saml. Authenticate for step 1. Updated user with UID: '%s'" % saml_user_uid found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 1. found_user_name: '%s'" % found_user_name user_authenticated = authenticationService.authenticate( found_user_name) if (user_authenticated == False): print "Saml. Authenticate for step 1. Failed to authenticate user: '******'" % found_user_name return False print "Saml. Authenticate for step 1. Setting count steps to 1" context.set("saml_count_login_steps", 1) post_login_result = self.samlExtensionPostLogin( configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 1. post_login_result: '%s'" % post_login_result return post_login_result elif (saml_enroll_all_user_attr): # Convert SAML response to user entry newUser = self.getMappedAllAttributesUser( saml_response_attributes) saml_user_uid = self.getNameId(samlResponse, newUser) if saml_user_uid == None: return False self.setDefaultUid(newUser, saml_user_uid) newUser.setAttribute("oxExternalUid", "saml:%s" % saml_user_uid) print "Saml. Authenticate for step 1. Attempting to find user by oxExternalUid: saml:%s" % saml_user_uid # Check if there is user with specified saml_user_uid find_user_by_uid = userService.getUserByAttribute( "oxExternalUid", "saml:%s" % saml_user_uid) if (find_user_by_uid == None): # Auto user enrollment print "Saml. Authenticate for step 1. There is no user in LDAP. Adding user to local LDAP" print "Saml. Authenticate for step 1. Attempting to add user '%s' with next attributes: '%s'" % ( saml_user_uid, newUser.getCustomAttributes()) user_unique = self.checkUserUniqueness(newUser) if not user_unique: print "Saml. Authenticate for step 1. Failed to add user: '******'. User not unique" % newUser.getUserId( ) facesMessages = FacesMessages.instance() facesMessages.add( StatusMessage.Severity.ERROR, "Failed to enroll. User with same key attributes exist already" ) FacesContext.getCurrentInstance().getExternalContext( ).getFlash().setKeepMessages(True) return False find_user_by_uid = userService.addUser(newUser, True) print "Saml. Authenticate for step 1. Added new user with UID: '%s'" % find_user_by_uid.getUserId( ) else: if self.updateUser: print "Saml. Authenticate for step 1. Attempting to update user '%s' with next attributes: '%s'" % ( saml_user_uid, newUser.getCustomAttributes()) find_user_by_uid.setCustomAttributes( newUser.getCustomAttributes()) userService.updateUser(find_user_by_uid) print "Saml. Authenticate for step 1. Updated user with UID: '%s'" % saml_user_uid found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 1. found_user_name: '%s'" % found_user_name user_authenticated = authenticationService.authenticate( found_user_name) if (user_authenticated == False): print "Saml. Authenticate for step 1. Failed to authenticate user" return False print "Saml. Authenticate for step 1. Setting count steps to 1" context.set("saml_count_login_steps", 1) post_login_result = self.samlExtensionPostLogin( configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 1. post_login_result: '%s'" % post_login_result return post_login_result else: if saml_user_uid == None: return False # Check if the is user with specified saml_user_uid print "Saml. Authenticate for step 1. Attempting to find user by uid: '%s'" % saml_user_uid find_user_by_uid = userService.getUser(saml_user_uid) if (find_user_by_uid == None): print "Saml. Authenticate for step 1. Failed to find user" return False found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 1. found_user_name: '%s'" % found_user_name user_authenticated = authenticationService.authenticate( found_user_name) if (user_authenticated == False): print "Saml. Authenticate for step 1. Failed to authenticate user" return False print "Saml. Authenticate for step 1. Setting count steps to 1" context.set("saml_count_login_steps", 1) post_login_result = self.samlExtensionPostLogin( configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 1. post_login_result: '%s'" % post_login_result return post_login_result elif (step == 2): print "Saml. Authenticate for step 2" sessionAttributes = context.get("sessionAttributes") if (sessionAttributes == None ) or not sessionAttributes.containsKey("saml_user_uid"): print "Saml. Authenticate for step 2. saml_user_uid is empty" return False saml_user_uid = sessionAttributes.get("saml_user_uid") passed_step1 = StringHelper.isNotEmptyString(saml_user_uid) if (not passed_step1): return False credentials = Identity.instance().getCredentials() user_name = credentials.getUsername() user_password = credentials.getPassword() logged_in = False if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)): logged_in = userService.authenticate(user_name, user_password) if (not logged_in): return False # Check if there is user which has saml_user_uid # Avoid mapping Saml account to more than one IDP account find_user_by_uid = userService.getUserByAttribute( "oxExternalUid", "saml:%s" % saml_user_uid) if (find_user_by_uid == None): # Add saml_user_uid to user one id UIDs find_user_by_uid = userService.addUserAttribute( user_name, "oxExternalUid", "saml:%s" % saml_user_uid) if (find_user_by_uid == None): print "Saml. Authenticate for step 2. Failed to update current user" return False post_login_result = self.samlExtensionPostLogin( configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 2. post_login_result: '%s'" % post_login_result return post_login_result else: found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 2. found_user_name: '%s'" % found_user_name if StringHelper.equals(user_name, found_user_name): post_login_result = self.samlExtensionPostLogin( configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 2. post_login_result: '%s'" % post_login_result return post_login_result return False else: return False
def authenticate(self, configurationAttributes, requestParameters, step): context = Contexts.getEventContext() authenticationService = AuthenticationService.instance() userService = UserService.instance() saml_map_user = False saml_enroll_user = False saml_enroll_all_user_attr = False # Use saml_deployment_type only if there is no attributes mapping if (configurationAttributes.containsKey("saml_deployment_type")): saml_deployment_type = StringHelper.toLowerCase( configurationAttributes.get( "saml_deployment_type").getValue2()) if (StringHelper.equalsIgnoreCase(saml_deployment_type, "map")): saml_map_user = True if (StringHelper.equalsIgnoreCase(saml_deployment_type, "enroll")): saml_enroll_user = True if (StringHelper.equalsIgnoreCase(saml_deployment_type, "enroll_all_attr")): saml_enroll_all_user_attr = True saml_allow_basic_login = False if (configurationAttributes.containsKey("saml_allow_basic_login")): saml_allow_basic_login = StringHelper.toBoolean( configurationAttributes.get( "saml_allow_basic_login").getValue2(), False) use_basic_auth = False if (saml_allow_basic_login): # Detect if user used basic authnetication method credentials = Identity.instance().getCredentials() user_name = credentials.getUsername() user_password = credentials.getPassword() if (StringHelper.isNotEmpty(user_name) and StringHelper.isNotEmpty(user_password)): use_basic_auth = True if ((step == 1) and saml_allow_basic_login and use_basic_auth): print "Saml. Authenticate for step 1. Basic authentication" context.set("saml_count_login_steps", 1) credentials = Identity.instance().getCredentials() user_name = credentials.getUsername() user_password = credentials.getPassword() logged_in = False if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)): userService = UserService.instance() logged_in = userService.authenticate(user_name, user_password) if (not logged_in): return False return True if (step == 1): print "Saml. Authenticate for step 1" currentSamlConfiguration = self.getCurrentSamlConfiguration( self.samlConfiguration, configurationAttributes, requestParameters) if (currentSamlConfiguration == None): print "Saml. Prepare for step 1. Client saml configuration is invalid" return False saml_response_array = requestParameters.get("SAMLResponse") if ArrayHelper.isEmpty(saml_response_array): print "Saml. Authenticate for step 1. saml_response is empty" return False saml_response = saml_response_array[0] print "Saml. Authenticate for step 1. saml_response: '%s'" % saml_response samlResponse = Response(currentSamlConfiguration) samlResponse.loadXmlFromBase64(saml_response) saml_validate_response = True if (configurationAttributes.containsKey("saml_validate_response")): saml_validate_response = StringHelper.toBoolean( configurationAttributes.get( "saml_validate_response").getValue2(), False) if (saml_validate_response): if (not samlResponse.isValid()): print "Saml. Authenticate for step 1. saml_response isn't valid" saml_response_name_id = samlResponse.getNameId() if (StringHelper.isEmpty(saml_response_name_id)): print "Saml. Authenticate for step 1. saml_response_name_id is invalid" return False print "Saml. Authenticate for step 1. saml_response_name_id: '%s'" % saml_response_name_id saml_response_attributes = samlResponse.getAttributes() print "Saml. Authenticate for step 1. attributes: '%s'" % saml_response_attributes # Use persistent Id as saml_user_uid saml_user_uid = saml_response_name_id if (saml_map_user): # Use mapping to local IDP user print "Saml. Authenticate for step 1. Attempting to find user by oxExternalUid: saml: '%s'" % saml_user_uid # Check if the is user with specified saml_user_uid find_user_by_uid = userService.getUserByAttribute( "oxExternalUid", "saml:" + saml_user_uid) if (find_user_by_uid == None): print "Saml. Authenticate for step 1. Failed to find user" print "Saml. Authenticate for step 1. Setting count steps to 2" context.set("saml_count_login_steps", 2) context.set("saml_user_uid", saml_user_uid) return True found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 1. found_user_name: '%s'" % found_user_name user_authenticated = authenticationService.authenticate( found_user_name) if (user_authenticated == False): print "Saml. Authenticate for step 1. Failed to authenticate user" return False print "Saml. Authenticate for step 1. Setting count steps to 1" context.set("saml_count_login_steps", 1) post_login_result = self.samlExtensionPostLogin( configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 1. post_login_result: '%s'" % post_login_result return post_login_result elif (saml_enroll_user): # Use auto enrollment to local IDP print "Saml. Authenticate for step 1. Attempting to find user by oxExternalUid: saml: '%s'" % saml_user_uid # Check if the is user with specified saml_user_uid find_user_by_uid = userService.getUserByAttribute( "oxExternalUid", "saml:" + saml_user_uid) if (find_user_by_uid == None): # Auto user enrollemnt print "Saml. Authenticate for step 1. There is no user in LDAP. Adding user to local LDAP" # Convert saml result attributes keys to lover case saml_response_normalized_attributes = HashMap() for saml_response_attribute_entry in saml_response_attributes.entrySet( ): saml_response_normalized_attributes.put( StringHelper.toLowerCase( saml_response_attribute_entry.getKey()), saml_response_attribute_entry.getValue()) currentAttributesMapping = self.prepareCurrentAttributesMapping( self.attributesMapping, configurationAttributes, requestParameters) print "Saml. Authenticate for step 1. Using next attributes mapping '%s'" % currentAttributesMapping newUser = User() # Set custom object classes if self.userObjectClasses != None: print "Saml. Authenticate for step 1. User custom objectClasses to add persons: '%s'" % Util.array2ArrayList( self.userObjectClasses) newUser.setCustomObjectClasses(self.userObjectClasses) for attributesMappingEntry in currentAttributesMapping.entrySet( ): idpAttribute = attributesMappingEntry.getKey() localAttribute = attributesMappingEntry.getValue() if self.debugEnrollment: print "Saml. Authenticate for step 1. Trying to map '%s' into '%s'" % ( idpAttribute, localAttribute) localAttributeValue = saml_response_normalized_attributes.get( idpAttribute) if (localAttributeValue != None): if self.debugEnrollment: print "Saml. Authenticate for step 1. Setting attribute '%s' value '%s'" % ( localAttribute, localAttributeValue) newUser.setAttribute(localAttribute, localAttributeValue) newUser.setAttribute("oxExternalUid", "saml:" + saml_user_uid) print "Saml. Authenticate for step 1. Attempting to add user '%s' with next attributes: '%s'" % ( saml_user_uid, newUser.getCustomAttributes()) user_unique = self.checkUserUniqueness(newUser) if not user_unique: print "Saml. Authenticate for step 1. Failed to add user: '******'. User not unique" % newUser.getAttribute( "uid") facesMessages = FacesMessages.instance() facesMessages.add( StatusMessage.Severity.ERROR, "Failed to enroll. User with same key attributes exist already" ) FacesContext.getCurrentInstance().getExternalContext( ).getFlash().setKeepMessages(True) return False find_user_by_uid = userService.addUser(newUser, True) print "Saml. Authenticate for step 1. Added new user with UID: '%s'" % find_user_by_uid.getUserId( ) found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 1. found_user_name: '%s'" % found_user_name user_authenticated = authenticationService.authenticate( found_user_name) if (user_authenticated == False): print "Saml. Authenticate for step 1. Failed to authenticate user: '******'" % found_user_name return False print "Saml. Authenticate for step 1. Setting count steps to 1" context.set("saml_count_login_steps", 1) post_login_result = self.samlExtensionPostLogin( configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 1. post_login_result: '%s'" % post_login_result return post_login_result elif (saml_enroll_all_user_attr): print "Saml. Authenticate for step 1. Attempting to find user by oxExternalUid: saml:" + saml_user_uid # Check if the is user with specified saml_user_uid find_user_by_uid = userService.getUserByAttribute( "oxExternalUid", "saml:" + saml_user_uid) if (find_user_by_uid == None): print "Saml. Authenticate for step 1. Failed to find user" user = User() # Set custom object classes if self.userObjectClasses != None: print "Saml. Authenticate for step 1. User custom objectClasses to add persons: '%s'" % Util.array2ArrayList( self.userObjectClasses) user.setCustomObjectClasses(self.userObjectClasses) customAttributes = ArrayList() for key in saml_response_attributes.keySet(): ldapAttributes = attributeService.getAllAttributes() for ldapAttribute in ldapAttributes: saml2Uri = ldapAttribute.getSaml2Uri() if (saml2Uri == None): saml2Uri = attributeService.getDefaultSaml2Uri( ldapAttribute.getName()) if (saml2Uri == key): attribute = CustomAttribute( ldapAttribute.getName()) attribute.setValues(attributes.get(key)) customAttributes.add(attribute) attribute = CustomAttribute("oxExternalUid") attribute.setValue("saml:" + saml_user_uid) customAttributes.add(attribute) user.setCustomAttributes(customAttributes) if (user.getAttribute("sn") == None): attribute = CustomAttribute("sn") attribute.setValue(saml_user_uid) customAttributes.add(attribute) if (user.getAttribute("cn") == None): attribute = CustomAttribute("cn") attribute.setValue(saml_user_uid) customAttributes.add(attribute) user_unique = self.checkUserUniqueness(user) if not user_unique: print "Saml. Authenticate for step 1. Failed to add user: '******'. User not unique" % newUser.getAttribute( "uid") facesMessages = FacesMessages.instance() facesMessages.add( StatusMessage.Severity.ERROR, "Failed to enroll. User with same key attributes exist already" ) FacesContext.getCurrentInstance().getExternalContext( ).getFlash().setKeepMessages(True) return False find_user_by_uid = userService.addUser(user, True) print "Saml. Authenticate for step 1. Added new user with UID: '%s'" % find_user_by_uid.getUserId( ) found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 1. found_user_name: '%s'" % found_user_name user_authenticated = authenticationService.authenticate( found_user_name) if (user_authenticated == False): print "Saml. Authenticate for step 1. Failed to authenticate user" return False print "Saml. Authenticate for step 1. Setting count steps to 1" context.set("saml_count_login_steps", 1) post_login_result = self.samlExtensionPostLogin( configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 1. post_login_result: '%s'" % post_login_result return post_login_result else: # Check if the is user with specified saml_user_uid print "Saml. Authenticate for step 1. Attempting to find user by uid: '%s'" % saml_user_uid find_user_by_uid = userService.getUser(saml_user_uid) if (find_user_by_uid == None): print "Saml. Authenticate for step 1. Failed to find user" return False found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 1. found_user_name: '%s'" % found_user_name user_authenticated = authenticationService.authenticate( found_user_name) if (user_authenticated == False): print "Saml. Authenticate for step 1. Failed to authenticate user" return False print "Saml. Authenticate for step 1. Setting count steps to 1" context.set("saml_count_login_steps", 1) post_login_result = self.samlExtensionPostLogin( configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 1. post_login_result: '%s'" % post_login_result return post_login_result elif (step == 2): print "Saml. Authenticate for step 2" sessionAttributes = context.get("sessionAttributes") if (sessionAttributes == None ) or not sessionAttributes.containsKey("saml_user_uid"): print "Saml. Authenticate for step 2. saml_user_uid is empty" return False saml_user_uid = sessionAttributes.get("saml_user_uid") passed_step1 = StringHelper.isNotEmptyString(saml_user_uid) if (not passed_step1): return False credentials = Identity.instance().getCredentials() user_name = credentials.getUsername() user_password = credentials.getPassword() logged_in = False if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)): logged_in = userService.authenticate(user_name, user_password) if (not logged_in): return False # Check if there is user which has saml_user_uid # Avoid mapping Saml account to more than one IDP account find_user_by_uid = userService.getUserByAttribute( "oxExternalUid", "saml:" + saml_user_uid) if (find_user_by_uid == None): # Add saml_user_uid to user one id UIDs find_user_by_uid = userService.addUserAttribute( user_name, "oxExternalUid", "saml:" + saml_user_uid) if (find_user_by_uid == None): print "Saml. Authenticate for step 2. Failed to update current user" return False post_login_result = self.samlExtensionPostLogin( configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 2. post_login_result: '%s'" % post_login_result return post_login_result else: found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 2. found_user_name: '%s'" % found_user_name if StringHelper.equals(user_name, found_user_name): post_login_result = self.samlExtensionPostLogin( configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 2. post_login_result: '%s'" % post_login_result return post_login_result return False else: return False
def processOtpAuthentication(self, requestParameters, user_name, session_attributes, otp_auth_method): facesMessages = FacesMessages.instance() FacesContext.getCurrentInstance().getExternalContext().getFlash().setKeepMessages(True) userService = Component.getInstance(UserService) otpCode = ServerUtil.getFirstValue(requestParameters, "loginForm:otpCode") if StringHelper.isEmpty(otpCode): facesMessages.add(StatusMessage.Severity.ERROR, "Failed to authenticate. OTP code is empty") print "OTP. Process OTP authentication. otpCode is empty" return False if otp_auth_method == "enroll": # Get key from session otp_secret_key_encoded = session_attributes.get("otp_secret_key") if otp_secret_key_encoded == None: print "OTP. Process OTP authentication. OTP secret key is invalid" return False otp_secret_key = self.fromBase64Url(otp_secret_key_encoded) if self.otpType == "hotp": validation_result = self.validateHotpKey(otp_secret_key, 1, otpCode) if (validation_result != None) and validation_result["result"]: print "OTP. Process HOTP authentication during enrollment. otpCode is valid" # Store HOTP Secret Key and moving factor in user entry otp_user_external_uid = "hotp:%s;%s" % ( otp_secret_key_encoded, validation_result["movingFactor"] ) # Add otp_user_external_uid to user's external GUID list find_user_by_external_uid = userService.addUserAttribute(user_name, "oxExternalUid", otp_user_external_uid) if find_user_by_external_uid != None: return True print "OTP. Process HOTP authentication during enrollment. Failed to update user entry" elif self.otpType == "totp": validation_result = self.validateTotpKey(otp_secret_key, otpCode) if (validation_result != None) and validation_result["result"]: print "OTP. Process TOTP authentication during enrollment. otpCode is valid" # Store TOTP Secret Key and moving factor in user entry otp_user_external_uid = "totp:%s" % otp_secret_key_encoded # Add otp_user_external_uid to user's external GUID list find_user_by_external_uid = userService.addUserAttribute(user_name, "oxExternalUid", otp_user_external_uid) if find_user_by_external_uid != None: return True print "OTP. Process TOTP authentication during enrollment. Failed to update user entry" elif otp_auth_method == "authenticate": user_enrollments = self.findEnrollments(user_name) if len(user_enrollments) == 0: print "OTP. Process OTP authentication. There is no OTP enrollment for user '%s'" % user_name facesMessages.add(StatusMessage.Severity.ERROR, "There is no valid OTP user enrollments") return False if self.otpType == "hotp": for user_enrollment in user_enrollments: user_enrollment_data = user_enrollment.split(";") otp_secret_key_encoded = user_enrollment_data[0] # Get current moving factor from user entry moving_factor = StringHelper.toInteger(user_enrollment_data[1]) otp_secret_key = self.fromBase64Url(otp_secret_key_encoded) # Validate TOTP validation_result = self.validateHotpKey(otp_secret_key, moving_factor, otpCode) if (validation_result != None) and validation_result["result"]: print "OTP. Process HOTP authentication during authentication. otpCode is valid" otp_user_external_uid = "hotp:%s;%s" % ( otp_secret_key_encoded, moving_factor ) new_otp_user_external_uid = "hotp:%s;%s" % ( otp_secret_key_encoded, validation_result["movingFactor"] ) # Update moving factor in user entry find_user_by_external_uid = userService.replaceUserAttribute(user_name, "oxExternalUid", otp_user_external_uid, new_otp_user_external_uid) if find_user_by_external_uid != None: return True print "OTP. Process HOTP authentication during authentication. Failed to update user entry" elif self.otpType == "totp": for user_enrollment in user_enrollments: otp_secret_key = self.fromBase64Url(user_enrollment) # Validate TOTP validation_result = self.validateTotpKey(otp_secret_key, otpCode) if (validation_result != None) and validation_result["result"]: print "OTP. Process TOTP authentication during authentication. otpCode is valid" return True facesMessages.add(StatusMessage.Severity.ERROR, "Failed to authenticate. OTP code is invalid") print "OTP. Process OTP authentication. OTP code is invalid" return False
def processOtpAuthentication(self, requestParameters, user_name, session_attributes, otp_auth_method): facesMessages = FacesMessages.instance() FacesContext.getCurrentInstance().getExternalContext().getFlash().setKeepMessages(True) userService = UserService.instance() otpCode = ServerUtil.getFirstValue(requestParameters, "loginForm:otpCode") if StringHelper.isEmpty(otpCode): facesMessages.add(StatusMessage.Severity.ERROR, "Failed to authenticate. OTP code is empty") print "OTP. Process OTP authentication. otpCode is empty" return False if otp_auth_method == "enroll": # Get key from session otp_secret_key_encoded = session_attributes.get("otp_secret_key") if otp_secret_key_encoded == None: print "OTP. Process OTP authentication. OTP secret key is invalid" return False otp_secret_key = self.fromBase64Url(otp_secret_key_encoded) if self.otpType == "hotp": validation_result = self.validateHotpKey(otp_secret_key, 1, otpCode) if (validation_result != None) and validation_result["result"]: print "OTP. Process HOTP authentication during enrollment. otpCode is valid" # Store HOTP Secret Key and moving factor in user entry otp_user_external_uid = "hotp:%s;%s" % ( otp_secret_key_encoded, validation_result["movingFactor"] ) # Add otp_user_external_uid to user's external GUID list find_user_by_external_uid = userService.addUserAttribute(user_name, "oxExternalUid", otp_user_external_uid) if find_user_by_external_uid != None: return True print "OTP. Process HOTP authentication during enrollment. Failed to update user entry" elif self.otpType == "totp": validation_result = self.validateTotpKey(otp_secret_key, otpCode) if (validation_result != None) and validation_result["result"]: print "OTP. Process TOTP authentication during enrollment. otpCode is valid" # Store TOTP Secret Key and moving factor in user entry otp_user_external_uid = "totp:%s" % otp_secret_key_encoded # Add otp_user_external_uid to user's external GUID list find_user_by_external_uid = userService.addUserAttribute(user_name, "oxExternalUid", otp_user_external_uid) if find_user_by_external_uid != None: return True print "OTP. Process TOTP authentication during enrollment. Failed to update user entry" elif otp_auth_method == "authenticate": user_enrollments = self.findEnrollments(user_name) if len(user_enrollments) == 0: print "OTP. Process OTP authentication. There is no OTP enrollment for user '%s'" % user_name facesMessages.add(StatusMessage.Severity.ERROR, "There is no valid OTP user enrollments") return False if self.otpType == "hotp": for user_enrollment in user_enrollments: user_enrollment_data = user_enrollment.split(";") otp_secret_key_encoded = user_enrollment_data[0] # Get current moving factor from user entry moving_factor = StringHelper.toInteger(user_enrollment_data[1]) otp_secret_key = self.fromBase64Url(otp_secret_key_encoded) # Validate TOTP validation_result = self.validateHotpKey(otp_secret_key, moving_factor, otpCode) if (validation_result != None) and validation_result["result"]: print "OTP. Process HOTP authentication during authentication. otpCode is valid" otp_user_external_uid = "hotp:%s;%s" % ( otp_secret_key_encoded, moving_factor ) new_otp_user_external_uid = "hotp:%s;%s" % ( otp_secret_key_encoded, validation_result["movingFactor"] ) # Update moving factor in user entry find_user_by_external_uid = userService.replaceUserAttribute(user_name, "oxExternalUid", otp_user_external_uid, new_otp_user_external_uid) if find_user_by_external_uid != None: return True print "OTP. Process HOTP authentication during authentication. Failed to update user entry" elif self.otpType == "totp": for user_enrollment in user_enrollments: otp_secret_key = self.fromBase64Url(user_enrollment) # Validate TOTP validation_result = self.validateTotpKey(otp_secret_key, otpCode) if (validation_result != None) and validation_result["result"]: print "OTP. Process TOTP authentication during authentication. otpCode is valid" return True facesMessages.add(StatusMessage.Severity.ERROR, "Failed to authenticate. OTP code is invalid") print "OTP. Process OTP authentication. OTP code is invalid" return False
def authenticate(self, configurationAttributes, requestParameters, step): if (step == 1): print("Basic (multi auth conf & lock account). Authenticate for step 1") credentials = Identity.instance().getCredentials() keyValue = credentials.getUsername() userPassword = credentials.getPassword() if not StringHelper.isNotEmptyString(keyValue) or not StringHelper.isNotEmptyString(userPassword): print("Basic (multi auth conf & lock account). Missing fields ") faces_messages = FacesMessages.instance() faces_messages.clear() FacesContext.getCurrentInstance().getExternalContext().getFlash().setKeepMessages(True) faces_messages.addFromResourceBundle( FacesMessage.SEVERITY_ERROR, "login.missingField") return False keyValue = keyValue.strip() user_status = self.getUserAttributeValue(keyValue, "gluuStatus") if user_status is not None and user_status != "active": print("Basic (multi auth conf & lock account). Account locked for user '%s'" % keyValue) faces_messages = FacesMessages.instance() faces_messages.clear() FacesContext.getCurrentInstance().getExternalContext().getFlash().setKeepMessages(True) faces_messages.addFromResourceBundle( FacesMessage.SEVERITY_ERROR, "login.accountLocked") return False if (StringHelper.isNotEmptyString(keyValue) and StringHelper.isNotEmptyString(userPassword)): authenticationService = Component.getInstance( AuthenticationService) logged_in = False for ldapExtendedEntryManager in self.ldapExtendedEntryManagers: if logged_in: break ldapConfiguration = ldapExtendedEntryManager["ldapConfiguration"] ldapEntryManager = ldapExtendedEntryManager["ldapEntryManager"] loginAttributes = ldapExtendedEntryManager["loginAttributes"] localLoginAttributes = ldapExtendedEntryManager["localLoginAttributes"] print("Basic (multi auth conf & lock account). Authenticate for step 1. Using configuration: " + ldapConfiguration.getConfigId()) idx = 0 count = len(loginAttributes) while (idx < count): primaryKey = loginAttributes[idx] localPrimaryKey = localLoginAttributes[idx] loggedIn = authenticationService.authenticate( ldapConfiguration, ldapEntryManager, keyValue, userPassword, primaryKey, localPrimaryKey) if (loggedIn): logged_in = True break idx += 1 if logged_in: self.setUserAttributeValue( keyValue, self.invalidLoginCountAttribute, StringHelper.toString(0)) return True countInvalidLoginArributeValue = self.getUserAttributeValue( keyValue, self.invalidLoginCountAttribute) countInvalidLogin = StringHelper.toInteger( countInvalidLoginArributeValue, 0) if countInvalidLogin < self.maximumInvalidLoginAttemps: countInvalidLogin = countInvalidLogin + 1 self.setUserAttributeValue( keyValue, self.invalidLoginCountAttribute, StringHelper.toString(countInvalidLogin)) if countInvalidLogin >= self.maximumInvalidLoginAttemps: self.lockUser(keyValue) self.setUserAttributeValue( keyValue, self.invalidLoginCountAttribute, StringHelper.toString(0)) return False else: return False
def authenticate(self, configurationAttributes, requestParameters, step): context = Contexts.getEventContext() authenticationService = AuthenticationService.instance() userService = UserService.instance() saml_map_user = False saml_enroll_user = False saml_enroll_all_user_attr = False # Use saml_deployment_type only if there is no attributes mapping if (configurationAttributes.containsKey("saml_deployment_type")): saml_deployment_type = StringHelper.toLowerCase(configurationAttributes.get("saml_deployment_type").getValue2()) if (StringHelper.equalsIgnoreCase(saml_deployment_type, "map")): saml_map_user = True if (StringHelper.equalsIgnoreCase(saml_deployment_type, "enroll")): saml_enroll_user = True if (StringHelper.equalsIgnoreCase(saml_deployment_type, "enroll_all_attr")): saml_enroll_all_user_attr = True saml_allow_basic_login = False if (configurationAttributes.containsKey("saml_allow_basic_login")): saml_allow_basic_login = StringHelper.toBoolean(configurationAttributes.get("saml_allow_basic_login").getValue2(), False) use_basic_auth = False if (saml_allow_basic_login): # Detect if user used basic authnetication method credentials = Identity.instance().getCredentials() user_name = credentials.getUsername() user_password = credentials.getPassword() if (StringHelper.isNotEmpty(user_name) and StringHelper.isNotEmpty(user_password)): use_basic_auth = True if ((step == 1) and saml_allow_basic_login and use_basic_auth): print "Saml. Authenticate for step 1. Basic authentication" context.set("saml_count_login_steps", 1) credentials = Identity.instance().getCredentials() user_name = credentials.getUsername() user_password = credentials.getPassword() logged_in = False if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)): userService = UserService.instance() logged_in = userService.authenticate(user_name, user_password) if (not logged_in): return False return True if (step == 1): print "Saml. Authenticate for step 1" currentSamlConfiguration = self.getCurrentSamlConfiguration(self.samlConfiguration, configurationAttributes, requestParameters) if (currentSamlConfiguration == None): print "Saml. Prepare for step 1. Client saml configuration is invalid" return False saml_response_array = requestParameters.get("SAMLResponse") if ArrayHelper.isEmpty(saml_response_array): print "Saml. Authenticate for step 1. saml_response is empty" return False saml_response = saml_response_array[0] print "Saml. Authenticate for step 1. saml_response: '%s'" % saml_response samlResponse = Response(currentSamlConfiguration) samlResponse.loadXmlFromBase64(saml_response) saml_validate_response = True if (configurationAttributes.containsKey("saml_validate_response")): saml_validate_response = StringHelper.toBoolean(configurationAttributes.get("saml_validate_response").getValue2(), False) if (saml_validate_response): if (not samlResponse.isValid()): print "Saml. Authenticate for step 1. saml_response isn't valid" saml_response_attributes = samlResponse.getAttributes() print "Saml. Authenticate for step 1. attributes: '%s'" % saml_response_attributes if (saml_map_user): saml_user_uid = self.getSamlNameId(samlResponse) if saml_user_uid == None: return False # Use mapping to local IDP user print "Saml. Authenticate for step 1. Attempting to find user by oxExternalUid: saml: '%s'" % saml_user_uid # Check if the is user with specified saml_user_uid find_user_by_uid = userService.getUserByAttribute("oxExternalUid", "saml:%s" % saml_user_uid) if (find_user_by_uid == None): print "Saml. Authenticate for step 1. Failed to find user" print "Saml. Authenticate for step 1. Setting count steps to 2" context.set("saml_count_login_steps", 2) context.set("saml_user_uid", saml_user_uid) return True found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 1. found_user_name: '%s'" % found_user_name user_authenticated = authenticationService.authenticate(found_user_name) if (user_authenticated == False): print "Saml. Authenticate for step 1. Failed to authenticate user" return False print "Saml. Authenticate for step 1. Setting count steps to 1" context.set("saml_count_login_steps", 1) post_login_result = self.samlExtensionPostLogin(configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 1. post_login_result: '%s'" % post_login_result return post_login_result elif (saml_enroll_user): # Convert SAML response to user entry newUser = self.getMappedUser(configurationAttributes, requestParameters, saml_response_attributes) saml_user_uid = self.getNameId(samlResponse, newUser) if saml_user_uid == None: return False self.setDefaultUid(newUser, saml_user_uid) newUser.setAttribute("oxExternalUid", "saml:%s" % saml_user_uid) # Use auto enrollment to local IDP print "Saml. Authenticate for step 1. Attempting to find user by oxExternalUid: saml: '%s'" % saml_user_uid # Check if there is user with specified saml_user_uid find_user_by_uid = userService.getUserByAttribute("oxExternalUid", "saml:%s" % saml_user_uid) if find_user_by_uid == None: # Auto user enrollment print "Saml. Authenticate for step 1. There is no user in LDAP. Adding user to local LDAP" print "Saml. Authenticate for step 1. Attempting to add user '%s' with next attributes: '%s'" % (saml_user_uid, newUser.getCustomAttributes()) user_unique = self.checkUserUniqueness(newUser) if not user_unique: print "Saml. Authenticate for step 1. Failed to add user: '******'. User not unique" % newUser.getUserId() facesMessages = FacesMessages.instance() facesMessages.add(StatusMessage.Severity.ERROR, "Failed to enroll. User with same key attributes exist already") FacesContext.getCurrentInstance().getExternalContext().getFlash().setKeepMessages(True) return False find_user_by_uid = userService.addUser(newUser, True) print "Saml. Authenticate for step 1. Added new user with UID: '%s'" % find_user_by_uid.getUserId() else: if self.updateUser: print "Saml. Authenticate for step 1. Attempting to update user '%s' with next attributes: '%s'" % (saml_user_uid, newUser.getCustomAttributes()) find_user_by_uid.setCustomAttributes(newUser.getCustomAttributes()) userService.updateUser(find_user_by_uid) print "Saml. Authenticate for step 1. Updated user with UID: '%s'" % saml_user_uid found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 1. found_user_name: '%s'" % found_user_name user_authenticated = authenticationService.authenticate(found_user_name) if (user_authenticated == False): print "Saml. Authenticate for step 1. Failed to authenticate user: '******'" % found_user_name return False print "Saml. Authenticate for step 1. Setting count steps to 1" context.set("saml_count_login_steps", 1) post_login_result = self.samlExtensionPostLogin(configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 1. post_login_result: '%s'" % post_login_result return post_login_result elif (saml_enroll_all_user_attr): # Convert SAML response to user entry newUser = self.getMappedAllAttributesUser(saml_response_attributes) saml_user_uid = self.getNameId(samlResponse, newUser) if saml_user_uid == None: return False self.setDefaultUid(newUser, saml_user_uid) newUser.setAttribute("oxExternalUid", "saml:%s" % saml_user_uid) print "Saml. Authenticate for step 1. Attempting to find user by oxExternalUid: saml:%s" % saml_user_uid # Check if there is user with specified saml_user_uid find_user_by_uid = userService.getUserByAttribute("oxExternalUid", "saml:%s" % saml_user_uid) if (find_user_by_uid == None): # Auto user enrollment print "Saml. Authenticate for step 1. There is no user in LDAP. Adding user to local LDAP" print "Saml. Authenticate for step 1. Attempting to add user '%s' with next attributes: '%s'" % (saml_user_uid, newUser.getCustomAttributes()) user_unique = self.checkUserUniqueness(newUser) if not user_unique: print "Saml. Authenticate for step 1. Failed to add user: '******'. User not unique" % newUser.getUserId() facesMessages = FacesMessages.instance() facesMessages.add(StatusMessage.Severity.ERROR, "Failed to enroll. User with same key attributes exist already") FacesContext.getCurrentInstance().getExternalContext().getFlash().setKeepMessages(True) return False find_user_by_uid = userService.addUser(newUser, True) print "Saml. Authenticate for step 1. Added new user with UID: '%s'" % find_user_by_uid.getUserId() else: if self.updateUser: print "Saml. Authenticate for step 1. Attempting to update user '%s' with next attributes: '%s'" % (saml_user_uid, newUser.getCustomAttributes()) find_user_by_uid.setCustomAttributes(newUser.getCustomAttributes()) userService.updateUser(find_user_by_uid) print "Saml. Authenticate for step 1. Updated user with UID: '%s'" % saml_user_uid found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 1. found_user_name: '%s'" % found_user_name user_authenticated = authenticationService.authenticate(found_user_name) if (user_authenticated == False): print "Saml. Authenticate for step 1. Failed to authenticate user" return False print "Saml. Authenticate for step 1. Setting count steps to 1" context.set("saml_count_login_steps", 1) post_login_result = self.samlExtensionPostLogin(configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 1. post_login_result: '%s'" % post_login_result return post_login_result else: if saml_user_uid == None: return False # Check if the is user with specified saml_user_uid print "Saml. Authenticate for step 1. Attempting to find user by uid: '%s'" % saml_user_uid find_user_by_uid = userService.getUser(saml_user_uid) if (find_user_by_uid == None): print "Saml. Authenticate for step 1. Failed to find user" return False found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 1. found_user_name: '%s'" % found_user_name user_authenticated = authenticationService.authenticate(found_user_name) if (user_authenticated == False): print "Saml. Authenticate for step 1. Failed to authenticate user" return False print "Saml. Authenticate for step 1. Setting count steps to 1" context.set("saml_count_login_steps", 1) post_login_result = self.samlExtensionPostLogin(configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 1. post_login_result: '%s'" % post_login_result return post_login_result elif (step == 2): print "Saml. Authenticate for step 2" sessionAttributes = context.get("sessionAttributes") if (sessionAttributes == None) or not sessionAttributes.containsKey("saml_user_uid"): print "Saml. Authenticate for step 2. saml_user_uid is empty" return False saml_user_uid = sessionAttributes.get("saml_user_uid") passed_step1 = StringHelper.isNotEmptyString(saml_user_uid) if (not passed_step1): return False credentials = Identity.instance().getCredentials() user_name = credentials.getUsername() user_password = credentials.getPassword() logged_in = False if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)): logged_in = userService.authenticate(user_name, user_password) if (not logged_in): return False # Check if there is user which has saml_user_uid # Avoid mapping Saml account to more than one IDP account find_user_by_uid = userService.getUserByAttribute("oxExternalUid", "saml:%s" % saml_user_uid) if (find_user_by_uid == None): # Add saml_user_uid to user one id UIDs find_user_by_uid = userService.addUserAttribute(user_name, "oxExternalUid", "saml:%s" % saml_user_uid) if (find_user_by_uid == None): print "Saml. Authenticate for step 2. Failed to update current user" return False post_login_result = self.samlExtensionPostLogin(configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 2. post_login_result: '%s'" % post_login_result return post_login_result else: found_user_name = find_user_by_uid.getUserId() print "Saml. Authenticate for step 2. found_user_name: '%s'" % found_user_name if StringHelper.equals(user_name, found_user_name): post_login_result = self.samlExtensionPostLogin(configurationAttributes, find_user_by_uid) print "Saml. Authenticate for step 2. post_login_result: '%s'" % post_login_result return post_login_result return False else: return False