def prepareAttributesMapping(self, remoteAttributesList, localAttributesList):
        remoteAttributesListArray = StringHelper.split(remoteAttributesList, ",")
        if (ArrayHelper.isEmpty(remoteAttributesListArray)):
            print "Google+ PrepareAttributesMapping. There is no attributes specified in remoteAttributesList property"
            return None
        
        localAttributesListArray = StringHelper.split(localAttributesList, ",")
        if (ArrayHelper.isEmpty(localAttributesListArray)):
            print "Google+ PrepareAttributesMapping. There is no attributes specified in localAttributesList property"
            return None

        if (len(remoteAttributesListArray) != len(localAttributesListArray)):
            print "Google+ PrepareAttributesMapping. The number of attributes in remoteAttributesList and localAttributesList isn't equal"
            return None
        
        attributeMapping = IdentityHashMap()
        containsUid = False
        i = 0
        count = len(remoteAttributesListArray)
        while (i < count):
            remoteAttribute = StringHelper.toLowerCase(remoteAttributesListArray[i])
            localAttribute = StringHelper.toLowerCase(localAttributesListArray[i])
            attributeMapping.put(remoteAttribute, localAttribute)

            if (StringHelper.equalsIgnoreCase(localAttribute, "uid")):
                containsUid = True

            i = i + 1

        if (not containsUid):
            print "Google+ PrepareAttributesMapping. There is no mapping to mandatory 'uid' attribute"
            return None
        
        return attributeMapping
Esempio n. 2
0
    def attribute_mapping_function(azure_ad_attributes_list, gluu_ldap_attributes_list):
        try:
            azure_ad_attributes_list_array = StringHelper.split(azure_ad_attributes_list, ",")
            if ArrayHelper.isEmpty(azure_ad_attributes_list_array):
                print("AzureAD: There is no attributes specified in azure_ad_attributes_list property")
                return None

            gluu_ldap_attributes_list_array = StringHelper.split(gluu_ldap_attributes_list, ",")
            if ArrayHelper.isEmpty(gluu_ldap_attributes_list_array):
                print("AzureAD: There is no attributes specified in gluu_ldap_attributes_list property")
                return None

            if len(azure_ad_attributes_list_array) != len(gluu_ldap_attributes_list_array):
                print("AzureAD: The number of attributes isn't equal")
                return None

            attributes_map = IdentityHashMap()
            i = 0
            count = len(azure_ad_attributes_list_array)
            while i < count:
                azure_ad_attribute = StringHelper.toLowerCase(azure_ad_attributes_list_array[i])
                gluu_ldap_attribute = StringHelper.toLowerCase(gluu_ldap_attributes_list_array[i])
                attributes_map.put(azure_ad_attribute, gluu_ldap_attribute)
                i = i + 1

            return attributes_map
        except Exception, err:
            print("AzureAD: Exception inside prepareAttributesMapping " + str(err))
Esempio n. 3
0
    def init(self, configurationAttributes):
        print "Basic (multi login). Initialization"

        login_attributes_list_object = configurationAttributes.get("login_attributes_list")
        if (login_attributes_list_object == None):
            print "Basic (multi login). Initialization. There is no property login_attributes_list"
            return False

        login_attributes_list = login_attributes_list_object.getValue2()
        if (StringHelper.isEmpty(login_attributes_list)):
            print "Basic (multi login). Initialization. There is no attributes specified in login_attributes property"
            return False
        
        login_attributes_list_array = StringHelper.split(login_attributes_list, ",")
        if (ArrayHelper.isEmpty(login_attributes_list_array)):
            print "Basic (multi login). Initialization. There is no attributes specified in login_attributes property"
            return False

        if (configurationAttributes.containsKey("local_login_attributes_list")):
            local_login_attributes_list = configurationAttributes.get("local_login_attributes_list").getValue2()
            local_login_attributes_list_array = StringHelper.split(local_login_attributes_list, ",")
        else:
            print "Basic (multi login). Initialization. There is no property local_login_attributes_list. Assuming that login attributes are equal to local login attributes."
            local_login_attributes_list_array = login_attributes_list_array

        if (len(login_attributes_list_array) != len(local_login_attributes_list_array)):
            print "Basic (multi login). Initialization. The number of attributes in login_attributes_list and local_login_attributes_list isn't equal"
            return False
        
        self.login_attributes_list_array = login_attributes_list_array
        self.local_login_attributes_list_array = local_login_attributes_list_array

        print "Basic (multi login). Initialized successfully"
        return True   
Esempio n. 4
0
    def prepareAttributesMapping(self, remoteAttributesList, localAttributesList):
        try:
            remoteAttributesListArray = StringHelper.split(remoteAttributesList, ",")
            if (ArrayHelper.isEmpty(remoteAttributesListArray)):
                print("Registration: PrepareAttributesMapping. There is no attributes specified in remoteAttributesList property")
                return None

            localAttributesListArray = StringHelper.split(localAttributesList, ",")
            if (ArrayHelper.isEmpty(localAttributesListArray)):
                print("Registration: PrepareAttributesMapping. There is no attributes specified in localAttributesList property")
                return None

            if (len(remoteAttributesListArray) != len(localAttributesListArray)):
                print("Registration: PrepareAttributesMapping. The number of attributes in remoteAttributesList and localAttributesList isn't equal")
                return None

            attributeMapping = IdentityHashMap()
            containsUid = False
            i = 0
            count = len(remoteAttributesListArray)
            while (i < count):
                remoteAttribute = StringHelper.toLowerCase(remoteAttributesListArray[i])
                localAttribute = StringHelper.toLowerCase(localAttributesListArray[i])
                attributeMapping.put(remoteAttribute, localAttribute)

                i = i + 1

            return attributeMapping
        except Exception, err:
            print("Registration: Exception inside prepareAttributesMapping " + str(err))
    def authenticate(self, configurationAttributes, requestParameters, step):
        authenticationService = CdiUtil.bean(AuthenticationService)

        if (step == 1):
            print "Basic. Authenticate for step 1"

            identity = CdiUtil.bean(Identity)
            credentials = identity.getCredentials()
            
            user_name_array = StringHelper.split(credentials.getUsername(),"+")
            
            user_name = None
            
            if len(user_name_array) == 2:
                
                email_id_array = StringHelper.split(user_name_array[1],"@")
                user_name = user_name_array[0] + "@"+ email_id_array[1]
            else:
                
                user_name = user_name_array[0]
                
            print "Username for authentication is: %s  " % user_name
            user_password = credentials.getPassword()

            logged_in = False
            if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)):
                
                logged_in = authenticationService.authenticate(user_name, user_password,"mail","mail")
                
            if (not logged_in):
                return False

            return True
        else:
            return False
Esempio n. 6
0
    def prepareClientRedirectUris(self, configurationAttributes):
        clientRedirectUrisSet = HashSet()
        if not configurationAttributes.containsKey("client_redirect_uris"):
            return clientRedirectUrisSet

        clientRedirectUrisList = configurationAttributes.get(
            "client_redirect_uris").getValue2()
        if StringHelper.isEmpty(clientRedirectUrisList):
            print "Client registration. The property client_redirect_uris is empty"
            return clientRedirectUrisSet

        clientRedirectUrisArray = StringHelper.split(clientRedirectUrisList,
                                                     ",")
        if ArrayHelper.isEmpty(clientRedirectUrisArray):
            print "Client registration. No clients specified in client_redirect_uris property"
            return clientRedirectUrisSet

        # Convert to HashSet to quick search
        i = 0
        count = len(clientRedirectUrisArray)
        while i < count:
            uris = clientRedirectUrisArray[i]
            clientRedirectUrisSet.add(uris)
            i = i + 1

        return clientRedirectUrisSet
Esempio n. 7
0
    def prepareClientsSet(self, configurationAttributes):
        clientsSet = HashSet()
        if (not configurationAttributes.containsKey("allowed_clients")):
            return clientsSet

        allowedClientsList = configurationAttributes.get(
            "allowed_clients").getValue2()
        if (StringHelper.isEmpty(allowedClientsList)):
            print "UmaRptPolicy. The property allowed_clients is empty"
            return clientsSet

        allowedClientsListArray = StringHelper.split(allowedClientsList, ",")
        if (ArrayHelper.isEmpty(allowedClientsListArray)):
            print "UmaRptPolicy. No clients specified in allowed_clients property"
            return clientsSet

        # Convert to HashSet to quick search
        i = 0
        count = len(allowedClientsListArray)
        while (i < count):
            client = allowedClientsListArray[i]
            clientsSet.add(client)
            i = i + 1

        return clientsSet
    def prepareUserObjectClasses(self, configurationAttributes):
        user_object_classes = configurationAttributes.get("user_object_classes").getValue2()

        user_object_classes_list_array = StringHelper.split(user_object_classes, ",")
        if ArrayHelper.isEmpty(user_object_classes_list_array):
            return None
        
        return user_object_classes_list_array
    def prepareUserEnforceUniquenessAttributes(self, configurationAttributes):
        enforce_uniqueness_attr_list = configurationAttributes.get("enforce_uniqueness_attr_list").getValue2()

        enforce_uniqueness_attr_list_array = StringHelper.split(enforce_uniqueness_attr_list, ",")
        if ArrayHelper.isEmpty(enforce_uniqueness_attr_list_array):
            return None
        
        return enforce_uniqueness_attr_list_array
Esempio n. 10
0
    def init(self, configurationAttributes):

        print "Casa. init called"
        self.authenticators = {}
        self.configFileLocation = "/etc/gluu/conf/casa.json"
        self.uid_attr = self.getLocalPrimaryKey()

        custScriptService = CdiUtil.bean(CustomScriptService)
        self.scriptsList = custScriptService.findCustomScripts(
            Collections.singletonList(CustomScriptType.PERSON_AUTHENTICATION),
            "oxConfigurationProperty", "displayName", "oxEnabled", "oxLevel")
        dynamicMethods = self.computeMethods(self.scriptsList)

        if len(dynamicMethods) > 0:
            print "Casa. init. Loading scripts for dynamic modules: %s" % dynamicMethods

            for acr in dynamicMethods:
                moduleName = self.modulePrefix + acr
                try:
                    external = __import__(moduleName, globals(), locals(),
                                          ["PersonAuthentication"], -1)
                    module = external.PersonAuthentication(
                        self.currentTimeMillis)

                    print "Casa. init. Got dynamic module for acr %s" % acr
                    configAttrs = self.getConfigurationAttributes(
                        acr, self.scriptsList)

                    if acr == self.ACR_U2F:
                        u2f_application_id = configurationAttributes.get(
                            "u2f_app_id").getValue2()
                        configAttrs.put(
                            "u2f_application_id",
                            SimpleCustomProperty("u2f_application_id",
                                                 u2f_application_id))
                    elif acr == self.ACR_SG:
                        application_id = configurationAttributes.get(
                            "supergluu_app_id").getValue2()
                        configAttrs.put(
                            "application_id",
                            SimpleCustomProperty("application_id",
                                                 application_id))

                    if module.init(configAttrs):
                        module.configAttrs = configAttrs
                        self.authenticators[acr] = module
                    else:
                        print "Casa. init. Call to init in module '%s' returned False" % moduleName
                except:
                    print "Casa. init. Failed to load module %s" % moduleName
                    print "Exception: ", sys.exc_info()[1]

            mobile_methods = configurationAttributes.get("mobile_methods")
            self.mobile_methods = [] if mobile_methods == None else StringHelper.split(
                mobile_methods.getValue2(), ",")

        print "Casa. init. Initialized successfully"
        return True
Esempio n. 11
0
    def update(self, dynamicScopeContext, configurationAttributes):
        print "Dynamic scope [saml_nameid_scope]. Update method"

        # Get the client and SAML affilitation value
        authorizationGrant = dynamicScopeContext.getAuthorizationGrant()
        oidcClient = authorizationGrant.getClient()
        samlSpNameQualifier = oidcClient.getPolicyUri()

        # if samlSpNameQualifier is not empty, we pass the affiliated SAML nameid
        if (samlSpNameQualifier != None):
            # then we look for the SAML persistentId value in user profile
            print "Dynamic scope [saml_nameid_scope]. Found SPNameQualifier parameter '%s'" % samlSpNameQualifier
            user = dynamicScopeContext.getUser()
            userPersistentIds = user.getAttributeValues("persistentId")
            print "Dynamic scope [saml_nameid_scope]. Found SPNameQualifier parameter"
            if (userPersistentIds != None):
                if (userPersistentIds.size > 0):
                    # go through existing user persistentIds
                    for userPersistentId in userPersistentIds:
                        # if the current RP already has a mapping then skip the second phase
                        if (userPersistentId.find(samlSpNameQualifier) > -1):
                            print "Dynamic scope [saml_nameid_scope]. Found matching persistentId '%s'" % userPersistentId
                            # Format is : persistentIdSamlSpNQ|persistentIdIdp|persistentIdUid
                            samlSpNameQualifier = StringHelper.split(
                                userPersistentId, '|')[0]
                            samlIDPNameQualifier = StringHelper.split(
                                userPersistentId, '|')[1]
                            samlSpNameIDSubject = StringHelper.split(
                                userPersistentId, '|')[2]
                            # create a JSON object with the full NameID object
                            samlNameIdJson = '{"SPNameQualifier":"%s","NameQualifier":"%s","value":"%s"}' % (
                                samlSpNameQualifier, samlIDPNameQualifier,
                                samlSpNameIDSubject)
                            samlNameId = JSONObject(samlNameIdJson)
                            # Add the saml_nameid value to the result if present
                            jsonWebResponse = dynamicScopeContext.getJsonWebResponse(
                            )
                            claims = jsonWebResponse.getClaims()
                            claims.setClaim("saml_nameid", samlNameId)

        return True
    def processMappingCollectionFilters(self, attrs):
        param_idp = attrs.get("idp_to_collect_old_mappings_from")
        param_rps = attrs.get("rps_to_collect_old_mappings_for")

        self.idp_to_collect_old_mappings_from = []
        self.rps_to_collect_old_mappings_for  = []

        # COLLECT - Parse the list of RPs and IDP that we need to collect for
        if param_idp != None and param_rps != None:
            idpList = param_idp.getValue2()
            rpList = param_rps.getValue2()

            if StringHelper.isNotEmpty(idpList) and StringHelper.isNotEmpty(rpList):
                self.idp_to_collect_old_mappings_from = StringHelper.split(idpList,',')
                self.rps_to_collect_old_mappings_for  = StringHelper.split(rpList,',')
                print "Passport-saml. init. COLLECTING mappings for IDPs [ %s ]" % ', '.join(self.idp_to_collect_old_mappings_from)
                print "Passport-saml. init. COLLECTING mappings for RPs [ %s ]" % ', '.join(self.rps_to_collect_old_mappings_for)
                return True

        print "Passport-saml. init. NOT COLLECTING any mappings, parameters [idp_to_collect_old_mappings_from] and [rps_to_collect_old_mappings_for] missing/empty."
        return True
    def setClientScopes(self, client, requiredScopes):
        
        if requiredScopes == None:
            print "Casa client registration. No list of scopes was passed in script parameters"
            return

        requiredScopes = StringHelper.split(requiredScopes.getValue2(), ",")
        newScopes = client.getScopes()
        scopeService = CdiUtil.bean(ScopeService)

        for scopeName in requiredScopes:
            scope = scopeService.getScopeById(scopeName)
            if not scope.isDefaultScope():
                print "Casa client registration. Adding scope '%s'" % scopeName
                newScopes = ArrayHelper.addItemToStringArray(newScopes, scope.getDn())

        print "Casa client registration. Result scopes are: %s" % newScopes
        client.setScopes(newScopes)
    def setClientScopes(self, client, requiredScopes):
        
        if requiredScopes == None:
            print "Casa client registration. No list of scopes was passed in script parameters"
            return

        requiredScopes = StringHelper.split(requiredScopes.getValue2(), ",")
        newScopes = client.getScopes()
        scopeService = CdiUtil.bean(ScopeService)

        for scopeName in requiredScopes:
            scope = scopeService.getScopeById(scopeName)
            if not scope.isDefaultScope():
                print "Casa client registration. Adding scope '%s'" % scopeName
                newScopes = ArrayHelper.addItemToStringArray(newScopes, scope.getDn())

        print "Casa client registration. Result scopes are: %s" % newScopes
        client.setScopes(newScopes)
    def init(self, configurationAttributes):

        print "Casa. init called"
        self.authenticators = {}
        self.configFileLocation = "/etc/gluu/conf/casa.json"
        self.uid_attr = self.getLocalPrimaryKey()

        custScriptService = CdiUtil.bean(CustomScriptService)
        self.scriptsList = custScriptService.findCustomScripts(Collections.singletonList(CustomScriptType.PERSON_AUTHENTICATION), "oxConfigurationProperty", "displayName", "gluuStatus", "oxLevel")
        dynamicMethods = self.computeMethods(self.scriptsList)

        if len(dynamicMethods) > 0:
            print "Casa. init. Loading scripts for dynamic modules: %s" % dynamicMethods

            for acr in dynamicMethods:
                moduleName = self.modulePrefix + acr
                try:
                    external = __import__(moduleName, globals(), locals(), ["PersonAuthentication"], -1)
                    module = external.PersonAuthentication(self.currentTimeMillis)

                    print "Casa. init. Got dynamic module for acr %s" % acr
                    configAttrs = self.getConfigurationAttributes(acr, self.scriptsList)

                    if acr == self.ACR_U2F:
                        u2f_application_id = configurationAttributes.get("u2f_app_id").getValue2()
                        configAttrs.put("u2f_application_id", SimpleCustomProperty("u2f_application_id", u2f_application_id))
                    elif acr == self.ACR_SG:
                        client_redirect_uri = configurationAttributes.get("supergluu_app_id").getValue2()
                        configAttrs.put("client_redirect_uri", SimpleCustomProperty("client_redirect_uri", client_redirect_uri))

                    if module.init(configAttrs):
                        module.configAttrs = configAttrs
                        self.authenticators[acr] = module
                    else:
                        print "Casa. init. Call to init in module '%s' returned False" % moduleName
                except:
                    print "Casa. init. Failed to load module %s" % moduleName
                    print "Exception: ", sys.exc_info()[1]

            mobile_methods = configurationAttributes.get("mobile_methods")
            self.mobile_methods = [] if mobile_methods == None else StringHelper.split(mobile_methods.getValue2(), ",")

        print "Casa. init. Initialized successfully"
        return True
Esempio n. 16
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        identity = CdiUtil.bean(Identity)
        session_attributes = identity.getSessionId().getSessionAttributes()
        authenticationService = CdiUtil.bean(AuthenticationService)
        allowedCountriesListArray = StringHelper.split(self.allowedCountries,
                                                       ",")
        if (len(allowedCountriesListArray) > 0
                and session_attributes.containsKey("remote_ip")):
            remote_ip = session_attributes.get("remote_ip")
            remote_loc_dic = self.determineGeolocationData(remote_ip)
            if remote_loc_dic == None:
                print "Super-Gluu. Prepare for step 2. Failed to determine remote location by remote IP '%s'" % remote_ip
                return
            remote_loc = "%s" % (remote_loc_dic['countryCode'])
            print "Your remote location is " + remote_loc
            if remote_loc in allowedCountriesListArray:
                print "you are allowed to access"
            else:
                return False

        if (step == 1):
            print "Basic. Authenticate for step 1"
            identity = CdiUtil.bean(Identity)
            credentials = identity.getCredentials()
            user_name = credentials.getUsername()
            user_password = credentials.getPassword()

            logged_in = False
            if (StringHelper.isNotEmptyString(user_name)
                    and StringHelper.isNotEmptyString(user_password)):
                logged_in = authenticationService.authenticate(
                    user_name, user_password)

            if (not logged_in):
                return False

            return True
        else:
            return False
Esempio n. 17
0
    def prepareClientsSet(self, configurationAttributes):
        clientsSet = HashSet()
        if (not configurationAttributes.containsKey("allowed_clients")):
            return clientsSet

        allowedClientsList = configurationAttributes.get("allowed_clients").getValue2()
        if (StringHelper.isEmpty(allowedClientsList)):
            print "UMA authorization policy. Initialization. The property allowed_clients is empty"
            return clientsSet    

        allowedClientsListArray = StringHelper.split(allowedClientsList, ",")
        if (ArrayHelper.isEmpty(allowedClientsListArray)):
            print "UMA authorization policy. Initialization. There aren't clients specified in allowed_clients property"
            return clientsSet
        
        # Convert to HashSet to quick search
        i = 0
        count = len(allowedClientsListArray)
        while (i < count):
            client = allowedClientsListArray[i]
            clientsSet.add(client)
            i = i + 1

        return clientsSet
    def prepareClientRedirectUris(self, configurationAttributes):
        clientRedirectUrisSet = HashSet()
        if not configurationAttributes.containsKey("client_redirect_uris"):
            return clientRedirectUrisSet

        clientRedirectUrisList = configurationAttributes.get("client_redirect_uris").getValue2()
        if StringHelper.isEmpty(clientRedirectUrisList):
            print "Casa client registration. The property client_redirect_uris is empty"
            return clientRedirectUrisSet    

        clientRedirectUrisArray = StringHelper.split(clientRedirectUrisList, ",")
        if ArrayHelper.isEmpty(clientRedirectUrisArray):
            print "Casa client registration. No clients specified in client_redirect_uris property"
            return clientRedirectUrisSet
        
        # Convert to HashSet to quick search
        i = 0
        count = len(clientRedirectUrisArray)
        while i < count:
            uris = clientRedirectUrisArray[i]
            clientRedirectUrisSet.add(uris)
            i = i + 1

        return clientRedirectUrisSet
    def attemptAuthentication(self, identity, user_profile, user_profile_json):

        uidKey = "uid"

        print "Passport-saml. attemptAuthentication. got session '%s'"  % identity.getSessionId().toString()
        sessionId = identity.getSessionId()
        sessionAttributes = sessionId.getSessionAttributes()
        collectSamlPass = sessionAttributes.get("collectSamlPass")
        switchFlowStatus = sessionAttributes.get("switchFlowStatus")

        if (collectSamlPass != 2):
            # COLLECT - Do not check user attributes if user has already been authenticated
            if not self.checkRequiredAttributes(user_profile, [uidKey, self.providerKey]):
                return False

        provider = user_profile[self.providerKey]
        if not provider in self.registeredProviders:
            print "Passport-saml. attemptAuthentication. Identity Provider %s not recognized" % provider
            return False

        # We assign the UID from the response as the SAML uid by default
        uid = user_profile[uidKey][0]

        # PERSISTENT_ID - save the original one generated by passport for collection purposes in second pass
        passportPersistentId = user_profile["persistentId"][0]
        # PERSISTENT_ID - generate the persistentId for the RP in case there is no further processing/collection happening (SAML only)
        newPersistentId = None
        newPersistentIdRp = sessionAttributes.get("spNameQualifier")
        if ( newPersistentIdRp != None and StringHelper.isNotEmptyString(newPersistentIdRp) ):
            newPersistentIdIdp = self.registeredProviders[provider]["issuer"]
            newPersistentIdUid = "sic" + uuid.uuid4().hex
            newPersistentId = '%s|%s|%s' % (newPersistentIdRp, newPersistentIdIdp, newPersistentIdUid )
        else:
            print "WARNING! The 'spNameQualifier' attribute from SHIBBOLETH is empty, no persistentId will be generated"

        # COLLECT - do NOT generate a new persistentId if collecting
        if  ( collectSamlPass != None and newPersistentId != None  ):
            user_profile["persistentId"][0] = newPersistentId
        # SWITCH - do NOT generate a new persistentId if the switch flow is being executed
        elif( switchFlowStatus == None and newPersistentId != None ):
            user_profile["persistentId"][0] = newPersistentId
        else:
            user_profile.pop("persistentId");

        # COLLECT - In this block we manipulate the "uid" and "persistentId" according to login or capturing pass
        if (collectSamlPass == 1):

            # The first time around we save the UID in the session parameter
            print "Passport-saml. attemptAuthentication. COLLECTING - First Pass. Saving original UID in session as '%s'"  % uid
            sessionAttributes.put("collect_originalUid", uid)

            # Removing persistentId from initial save because we need to run collection first
            print "Passport-saml. attemptAuthentication. COLLECTING - First Pass. Saving generated PersistentId for second pass to '%s'"  % user_profile["persistentId"][0]
            sessionAttributes.put("collect_generatedPersistentId", user_profile["persistentId"][0])
            user_profile.pop("persistentId")

        elif (collectSamlPass == 2):
            # The second time around we retrieve the saved UID
            print "Passport-saml. attemptAuthentication. COLLECTING - Second Pass. Authenticated for collection as '%s'"  % uid

            # Here we verify if there was no answer (GCKey) because allowCreate=false
            if (user_profile == None):
                print "Passport-saml. attemptAuthentication. Aw Crap, user_profile in response is None for original UID '%s'"  % uid
            elif (user_profile[uidKey] == None):
                print "Passport-saml. attemptAuthentication. Aw Crap, user_profile[uidKey] in response is None for original UID '%s'"  % uid
                #user_profile[persistentId] = []
                #user_profile[persistentId].append(generatedPersistentId)
            elif (user_profile[uidKey][0] == None):
                print "Passport-saml. attemptAuthentication. Aw Crap, user_profile[uidKey][0] in response is None for original UID '%s'"  % uid
            else:
                # COLLECT - Collect the persistent ID / PAI for the RP here
                # 1. take old persistentId and split by |
                # 2. replace the RP and keep provider and the PAI UID
                # 3. lastly put it back into the profile mapping and put the original UID back into the profile
                print "Passport-saml. attemptAuthentication. COLLECTING - Second Pass. Original persistentId from passport '%s'"  %  user_profile["persistentId"][0]
                rpPersistentId = passportPersistentId.split('|')
                newPersistentIdIdp = rpPersistentId[1]
                newPersistentIdUid = rpPersistentId[2]
                user_profile["persistentId"][0] = '%s|%s|%s' % (newPersistentIdRp, newPersistentIdIdp, newPersistentIdUid )
                print "Passport-saml. attemptAuthentication. COLLECTING - Second Pass. Collected persistentId '%s'"  % user_profile["persistentId"][0]

                uid = sessionAttributes.get("collect_originalUid")
                user_profile[uidKey][0] = uid
                print "Passport-saml. attemptAuthentication. COLLECTING - Second Pass. Setting profile to original UID '%s'"  % uid

            sessionAttributes.remove("collectSamlPass")
            sessionAttributes.remove("collect_originalUid")
            sessionAttributes.remove("collect_generatedPersistentId")

        externalUid = "passport-%s:%s:%s" % ("saml", provider, uid)

        print "Passport-saml. attemptAuthentication. Searching for user ExternalUID '%s'" % externalUid

        # MFA - save external UID to retrieve the user later
        sessionAttributes.put("auth_user_externalUid", externalUid)

        userService = CdiUtil.bean(UserService)
        userByUid = self.getUserByExternalUid(uid, provider, userService)


        # COLLECT - We will never use email in our data
        email = None
        if "mail" in user_profile:
            email = user_profile["mail"]
            if len(email) == 0:
                email = None
            else:
                email = email[0]
                user_profile["mail"] = [ email ]

        if email == None and self.registeredProviders[provider]["requestForEmail"]:
            print "Passport-saml. attemptAuthentication. Email was not received"

            if userByUid != None:
                # COLLECT - if collecting we check for existing persistentIds for RP to skip second call
                if (collectSamlPass == 1):
                    userPersistentIds = userByUid.getAttributeValues("persistentId")
                    if ( newPersistentIdRp != None and userPersistentIds != None ):
                        if ( userPersistentIds.size > 0 ):
                            # go through existing user persistentIds
                            for userPersistentId in userPersistentIds:
                                existingMappedRp = StringHelper.split(userPersistentId,'|')[0]
                                # if the current RP already has a mapping then skip the second phase
                                if ( userPersistentId.find(newPersistentIdRp) > -1 ):
                                    sessionAttributes.remove("selectedProvider")

                # This avoids asking for the email over every login attempt
                email = userByUid.getAttribute("mail")
                if email != None:
                    print "Passport-saml. attemptAuthentication. Filling missing email value with %s" % email
                    user_profile["mail"] = [ email ]

            if email == None:
                # Store user profile in session and abort this routine
                identity.setWorkingParameter("passport_user_profile", user_profile_json)
                return True

        # COLLECT - we will never store email addresses or match via EMAIL, skip to speed up processing
        # userByMail = None if email == None else userService.getUserByAttribute("mail", email)
        userByMail = None

        # Determine if we should add entry, update existing, or deny access
        doUpdate = False
        doAdd = False
        if userByUid != None:
            print "User with externalUid '%s' already exists" % externalUid
            if userByMail == None:
                doUpdate = True
            else:
                if userByMail.getUserId() == userByUid.getUserId():
                    doUpdate = True
                else:
                    print "Users with externalUid '%s' and mail '%s' are different. Access will be denied. Impersonation attempt?" % (externalUid, email)
                    self.setMessageError(FacesMessage.SEVERITY_ERROR, "Email value corresponds to an already existing provisioned account")
        else:
            if userByMail == None:
                doAdd = True
            elif self.registeredProviders[provider]["emailLinkingSafe"]:

                tmpList = userByMail.getAttributeValues("oxExternalUid")
                tmpList = ArrayList() if tmpList == None else ArrayList(tmpList)
                tmpList.add(externalUid)
                userByMail.setAttribute("oxExternalUid", tmpList)

                userByUid = userByMail
                print "External user supplying mail %s will be linked to existing account '%s'" % (email, userByMail.getUserId())
                doUpdate = True
            else:
                print "An attempt to supply an email of an existing user was made. Turn on 'emailLinkingSafe' if you want to enable linking"
                self.setMessageError(FacesMessage.SEVERITY_ERROR, "Email value corresponds to an already existing account. If you already have a username and password use those instead of an external authentication site to get access.")

        # MFA - precreate a new PAI for MFA
        if ( sessionAttributes.get("mfaFlowStatus") == "MFA_1_REQUIRED" ):
            # generate a new MFA PAI in case there is none in the user profile
            mfaUid = "mfa" + uuid.uuid4().hex
            user_profile[ "oxExternalUid_newMfa" ] = [ "passport-mfa:" + mfaUid ]

        username = None
        try:
            if doUpdate:
                username = userByUid.getUserId()
                user_profile[uidKey][0] = username
                print "Passport-saml. attemptAuthentication. Updating user %s" % username
                self.updateUser(userByUid, user_profile, userService)
            elif doAdd:
                print "Passport-saml. attemptAuthentication. Creating user %s" % externalUid
                user_profile[uidKey][0] = uuid.uuid4().hex
                newUser = self.addUser(externalUid, user_profile, userService)
                username = newUser.getUserId()
        except:
            print "Exception: ", sys.exc_info()[1]
            print "Passport-saml. attemptAuthentication. Authentication failed"
            return False

        if username == None:
            print "Passport-saml. attemptAuthentication. Authentication attempt was rejected"
            return False
        else:
            logged_in = CdiUtil.bean(AuthenticationService).authenticate(username)
            print "Passport-saml. attemptAuthentication. Authentication for %s returned %s" % (username, logged_in)
            if ( logged_in == True ):
                # Save the authenticated data
                sessionAttributes.put("authenticatedProvider", "passport_saml:" + provider)
                sessionAttributes.put("authenticatedUser", username)
                # SWITCH - Save contextual data for the switch flows
                if (switchFlowStatus == "1_GET_SOURCE"):
                    print "Passport-saml. attemptAuthentication. SWITCH FLOW: Setting SOURCE provider to %s" % sessionAttributes.get("authenticatedProvider")
                    sessionAttributes.put( "switchSourceAuthenticatedProvider", sessionAttributes.get("authenticatedProvider") )
                    sessionAttributes.put( "switchSourceAuthenticatedUser", username)
                elif (switchFlowStatus == "2_GET_TARGET"):
                    print "Passport-saml. attemptAuthentication. SWITCH FLOW: Setting TARGET provider to %s" % sessionAttributes.get("authenticatedProvider")
                    sessionAttributes.put("switchTargetAuthenticatedProvider", sessionAttributes.get("authenticatedProvider") )
                    sessionAttributes.put("switchTargetAuthenticatedUser", username)
                elif (sessionAttributes.get("mfaFlowStatus") == "MFA_1_REQUIRED"):
                    print "Passport-saml. attemptAuthentication. MFA FLOW: starting flow marking status = MFA_2_IN_PROGRESS"
                    sessionAttributes.put("mfaFlowStatus", "MFA_2_IN_PROGRESS")
                    sessionAttributes.put("selectedProvider", "mfa")

            ## SESSION_SAFE - update
            CdiUtil.bean(SessionIdService).updateSessionId(sessionId)

            return logged_in
Esempio n. 20
0
    def prepareForStep(self, configurationAttributes, requestParameters, step):
        print "IDP Chooser. prepareForStep called for step '%s'" % step

        identity = CdiUtil.bean(Identity)
        sessionId = identity.getSessionId()
        sessionAttributes = sessionId.getSessionAttributes()
        entityId = sessionAttributes.get("entityId")
        entitySpNameQualifier = sessionAttributes.get("spNameQualifier")

        # entityId is used for UI branding. Handle getting entityId if it's an OIDC client
        if (entityId == None):
            # First get the client_id (should be deterministic ... ?????)
            currentClientId = sessionAttributes.get("client_id")
            # Call the ClientService and get all clients
            clientService = CdiUtil.bean(ClientService)
            oidcClient = clientService.getClient(currentClientId)
            if (oidcClient != None):
                entityId = "oidc:%s" % oidcClient.getClientName()
                sessionAttributes.put("entityId", entityId)

            # SpNameQualifier is used for persistenId generation. Handle getting entitySpNameQualifier if it's an OIDC client
            if (entitySpNameQualifier == None):
                # Look for value saved in the PolicyURL field in the client configurationAttributes
                clientPolicyUri = oidcClient.getPolicyUri()
                if (StringHelper.isNotEmpty(clientPolicyUri)):
                    # Set it to the clientPolicyUri if absent
                    entitySpNameQualifier = clientPolicyUri
                    sessionAttributes.put("spNameQualifier", clientPolicyUri)
        # FIXME - For now as an error scenario if it's not found put a default
        if (entityId == None):
            entityId = "_default"

        # CUSTOMIZATION - Select which page body elements will be rendered
        if (sessionAttributes.get("pageContent") == None):
            # CUSTOMIZATION - FIRST try direct match
            pageContent = self.selectorPageContent.get(entityId)

            # CUSTOMIZATION - SECOND try prefix match
            if (pageContent == None):
                for contentKey in self.selectorPageContent.keys():
                    if (entityId.find(contentKey) == 0):
                        pageContent = self.selectorPageContent.get(contentKey)

            # CUSTOMIZATION - LASTLY go to default content
            if (pageContent == None):
                pageContent = self.selectorPageContent.get("_default")

            # CUSTOMIZATION - save the page content in session for reference in xhtml pages
            if (pageContent != None):
                sessionAttributes.put("pageContent", pageContent)
            else:
                # We have an error - log it and fail
                print "IDP Chooser. prepareForStep ERROR: '_default' and '%s' page content missing in file " % (
                    entityId,
                    configurationAttributes.get(
                        "selector_page_content_file").getValue2())
                return False

            # CUSTOMIZATION - Select which credential buttons will show up
            showCredentials = sessionAttributes.get(
                "pageContent")["credentials"]
            allCredentials = self.selectorPageContent["_default"][
                "credentials"]
            for cred in StringHelper.split(allCredentials, ','):
                if (showCredentials.find(cred) == -1):
                    sessionAttributes.put("hide_cred_" + cred, False)

        # SWITCH - update switch flow step if coming back with a user
        if (sessionAttributes.get("switchFlowStatus") == "1_GET_SOURCE"
                and sessionAttributes.get("auth_user") != None):
            # first get the source user and validate the persistentId exists for the entitySpNameQualifier
            userService = CdiUtil.bean(UserService)
            sourceUser = userService.getUser(
                sessionAttributes.get("switchSourceAuthenticatedUser"))
            # then find the persistenId for the entitySpNameQualifier in the source user
            sourcePersistentIds = sourceUser.getAttributeValues("persistentId")
            if (sourcePersistentIds != None):
                # go through source user persistentIds
                for userPersistentId in sourcePersistentIds:
                    existingMappedRp = StringHelper.split(
                        userPersistentId, '|')[0]
                    # if the current RP matches, save the persistenId for the target
                    if (userPersistentId.find(entitySpNameQualifier) > -1):
                        sessionAttributes.put("switchPersistentId",
                                              userPersistentId)

            print "IDP Chooser. prepareForStep SWITCH FLOW: setting 2_GET_TARGET"
            sessionAttributes.put("switchFlowStatus", "2_GET_TARGET")

        # SWITCH - move to switch screen if the target has been authenticated
        elif (sessionAttributes.get("switchFlowStatus") == "2_GET_TARGET"
              and sessionAttributes.get("auth_user") != None):
            # first get the target user
            userService = CdiUtil.bean(UserService)
            targetUser = userService.getUser(
                sessionAttributes.get("switchTargetAuthenticatedUser"))
            # then find the persistenId for the entitySpNameQualifier in the target user
            targetPersistentIds = targetUser.getAttributeValues("persistentId")
            switchCurrentState = "AVAILABLE"
            if (targetPersistentIds != None):
                # go through source user persistentIds
                for userPersistentId in targetPersistentIds:
                    existingMappedRp = StringHelper.split(
                        userPersistentId, '|')[0]
                    # if the current RP already has a persistentId then mark it
                    if (entitySpNameQualifier != None and
                            userPersistentId.find(entitySpNameQualifier) > -1):
                        switchCurrentState = "NOT AVAILABLE - Persistent ID already exists for this RP in the target"

            if (switchCurrentState == "AVAILABLE"):
                print "IDP Chooser. prepareForStep SWITCH FLOW: setting 3_DO_SWITCH"
                sessionAttributes.put("switchFlowStatus", "3_DO_SWITCH")
            else:
                print "IDP Chooser. prepareForStep SWITCH FLOW: FAILED - target contains mapping for %s" % entitySpNameQualifier
                sessionAttributes.put("switchFlowStatus", "4_FINISHED")

            sessionAttributes.put("switchCurrentState", switchCurrentState)

        # MFA - update mfa flow status - check if the entityId is on the list of MFA applications
        mfaFlowStatus = sessionAttributes.get("mfaFlowStatus")
        print "IDP Chooser. prepareForStep Fetched mfaFlowStatus = '%s'" % mfaFlowStatus
        for mfaEntityId in StringHelper.split(self.entityids_with_mfa, ','):
            if (mfaEntityId == entityId):
                # if the status is blank then we set it to MFA_1_REQUIRED. This also means first pass so no MFA forwarding
                if (mfaFlowStatus == None):
                    mfaFlowStatus = "MFA_1_REQUIRED"
                    print "IDP Chooser. prepareForStep Setting  mfaFlowStatus = '%s'" % mfaFlowStatus
                    sessionAttributes.put("mfaFlowStatus", mfaFlowStatus)

                # we check that we have an authenticated user, which is a signal to trigger MFA
                elif (sessionAttributes.get("auth_user") != None):
                    print "IDP Chooser. prepareForStep For mfaFlowStatus found authenticated user = '******'" % sessionAttributes.get(
                        "auth_user")
                    # SWITCH - we check that we are not in a switch flow, or switch flow has finished
                    switchFlowStatus = sessionAttributes.get(
                        "switchSourceAuthenticatedUser")
                    if (switchFlowStatus == None
                            or switchFlowStatus == "4_FINISHED"):
                        mfaFlowStatus = "MFA_2_IN_PROGRESS"
                        print "IDP Chooser. prepareForStep Setting  mfaFlowStatus = '%s' and [new_acr_value to 'passport_social'] and [selectedProvider to 'mfa']" % mfaFlowStatus
                        sessionAttributes.put("mfaFlowStatus", mfaFlowStatus)
                        print "IDP Chooser. prepareForStep Setting  [new_acr_value = 'passport_social'] and [selectedProvider = 'mfa']"
                        identity.setWorkingParameter("new_acr_value",
                                                     "passport_social")
                        sessionAttributes.put("selectedProvider", "mfa")

        ## SESSION_SAFE - update
        CdiUtil.bean(SessionIdService).updateSessionId(sessionId)

        print "IDP Chooser. prepareForStep. got session '%s'" % identity.getSessionId(
        ).toString()

        if (step == 1 or step == 2):
            return True
        else:
            return False
Esempio n. 21
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        print "IDP Chooser. authenticate called for step '%s'" % step

        identity = CdiUtil.bean(Identity)
        sessionId = identity.getSessionId()
        sessionAttributes = sessionId.getSessionAttributes()
        # SWITCH - if the switch credential is in 3_DO_SWITCH state, then do the switch
        if (sessionAttributes.get("switchFlowStatus") == "3_DO_SWITCH"):
            # first get the target user
            userService = CdiUtil.bean(UserService)
            sourceUser = userService.getUser(
                sessionAttributes.get("switchSourceAuthenticatedUser"))
            targetUser = userService.getUser(
                sessionAttributes.get("switchTargetAuthenticatedUser"))

            if (targetUser == None):
                print "IDP Chooser. authenticate: Failed to fetch target user '%s'" % sessionAttributes.get(
                    "switchTargetAuthenticatedUser")
                sessionAttributes.remove("switchFlowStatus")
                ## SESSION_SAFE - update
                CdiUtil.bean(SessionIdService).updateSessionId(sessionId)
                return False
            elif (sourceUser == None):
                print "IDP Chooser. authenticate: Failed to fetch source user '%s'" % sessionAttributes.get(
                    "switchSourceAuthenticatedUser")
                sessionAttributes.remove("switchFlowStatus")
                ## SESSION_SAFE - update
                CdiUtil.bean(SessionIdService).updateSessionId(sessionId)
                return False
            else:
                switchPersistentId = sessionAttributes.get(
                    "switchPersistentId")
                # FIRST set the persistentId for the entitySpNameQualifier in the target user
                tergetPersistentIds = targetUser.getAttributeValues(
                    "persistentId")
                tmpList = ArrayList(
                    tergetPersistentIds
                ) if tergetPersistentIds != None else ArrayList()
                tmpList.add(switchPersistentId)
                targetUser.setAttribute("persistentId", tmpList)
                userService.updateUser(targetUser)

                # SECOND remove the persistentId for the entitySpNameQualifier in the source user
                sourcePersistentIds = sourceUser.getAttributeValues(
                    "persistentId")
                tmpList = ArrayList()
                # build a new list of persistentIds without the switched ID
                for sourcePersistentId in sourcePersistentIds:
                    if (sourcePersistentId != switchPersistentId):
                        tmpList.add(
                            sessionAttributes.get("switchPersistentId"))
                sourceUser.setAttribute("persistentId", tmpList)
                try:
                    userService.updateUser(sourceUser)
                except:
                    # THIRD if failed to update the source then reset the source user
                    print "IDP Chooser. authenticate: Failed to update source user, '%s', reverting target user " % sessionAttributes.get(
                        "switchSourceAuthenticatedUser")
                    print "Exception: ", sys.exc_info()[1]
                    tergetPersistentIds = targetUser.getAttributeValues(
                        "persistentId")
                    tmpList = ArrayList(
                        tergetPersistentIds
                    ) if tergetPersistentIds != None else ArrayList()
                    tmpList.add(sessionAttributes.get("switchPersistentId"))
                    targetUser.setAttribute("persistentId", tmpList)
                    userService.updateUser(targetUser)
                    return False

                # finish the switch flow
                sessionAttributes.put("switchFlowStatus", "4_FINISHED")
                ## SESSION_SAFE - update
                return CdiUtil.bean(AuthenticationService).authenticate(
                    targetUser.getUserId())
        else:
            # process the ACR selection
            new_acr_provider_value = self.getAcrValueFromAuth(
                requestParameters)
            print "IDP Chooser. authenticate: saving new acr provider = '%s'" % new_acr_provider_value
            new_acr_provider_elements = StringHelper.split(
                new_acr_provider_value, ":")
            new_acr_value = new_acr_provider_elements[0]
            new_acr_provider = new_acr_provider_elements[1]
            print "IDP Chooser. authenticate: setting new_acr_value = '%s'" % new_acr_value
            print "IDP Chooser. authenticate: setting new_acr_provider = '%s'" % new_acr_provider

            # Validate the ACR is allowed for the current entityId/client
            allowedCredentials = sessionAttributes.get(
                "pageContent")["credentials"]
            allowSetNewAcr = False
            for cred in StringHelper.split(allowedCredentials, ','):
                if (new_acr_provider_value.find(cred) == -1):
                    allowSetNewAcr = True

            if (allowSetNewAcr):
                identity.setWorkingParameter("new_acr_value", new_acr_value)
                sessionAttributes.put("selectedProvider", new_acr_provider)
            else:
                print "IDP Chooser. authenticate: provider '%s' not allowed for this client" % new_acr_provider
                return False

            # SWITCH - Reading switch credential checkbox
            switchFlowStatus = sessionAttributes.get("switchFlowStatus")
            if (switchFlowStatus == None):
                switchSelected = self.getSwitchValueFromAuth(requestParameters)
                if (switchSelected == True):
                    print "IDP Chooser. authenticate SWITCH FLOW: setting 1_GET_SOURCE"
                    sessionAttributes.put("switchFlowStatus", "1_GET_SOURCE")

        ## SESSION_SAFE - update
        CdiUtil.bean(SessionIdService).updateSessionId(sessionId)

        if step == 1:
            return True
        else:
            return False
    def prepareForStep(self, configurationAttributes, requestParameters, step):

        extensionResult = self.extensionPrepareForStep(configurationAttributes, requestParameters, step)
        if extensionResult != None:
            return extensionResult

        print "Passport-social. prepareForStep called for step %s" % str(step)
        identity = CdiUtil.bean(Identity)
        sessionAttributes = identity.getSessionId().getSessionAttributes()
        sessionId = identity.getSessionId()

        if step == 1:
            identity.setWorkingParameter("externalProviders", json.dumps(self.registeredProviders))

            providerParam = self.customAuthzParameter
            providerFromSession = None
            url = None

            print "Passport-social. prepareForStep. got session '%s'" % identity.getSessionId().toString()

            sessionAttributes = identity.getSessionId().getSessionAttributes()
            self.skipProfileUpdate = StringHelper.equalsIgnoreCase(sessionAttributes.get("skipPassportProfileUpdate"), "true")
            
            # MFAgetCountAuthenticationSteps
            # 1. Check if there has been an authenticated user
            # 2. Check that mfa flow status is MFA_2_IN_PROGRESS
            # 3. Set the selected provider to "mfa"
            # 4. Get the MFA PAI from the user profile
            userService = CdiUtil.bean(UserService)
            mfaPai = None
            if ( sessionAttributes.get("auth_user") != None and sessionAttributes.get("mfaFlowStatus") == "MFA_2_IN_PROGRESS" ):
                # set the provider to "mfa"
                sessionAttributes.put("selectedProvider", "mfa")
                # get the MFA PAI from the external UID
                mfaOriginalUid = sessionAttributes.get( "authenticatedUser" )
                mfaUserByUid = userService.getUserByAttribute("uid", mfaOriginalUid)
                # go through the values to find the MFA PAI
                mfaUserOxExternalUids = mfaUserByUid.getAttributeValues("oxExternalUid")
                if (mfaUserOxExternalUids != None):
                    for mfaUserOxExternalUid in mfaUserOxExternalUids:
                        if ( mfaUserOxExternalUid.find("passport-mfa:") > -1 ):
                            mfaPai = StringHelper.split(mfaUserOxExternalUid,':')[1]
                print "Passport-social. prepareForStep. Using mfaPai = '%s'" % mfaPai
            elif ( sessionAttributes.get("selectedProvider") == "mfa"):
                print "Passport-social. prepareForStep. ERROR: 'selectedProvider' is 'mfa' but not in the MFA flow, Exiting"
                return False

            # This is added to the script by a previous module if the provider is preselected
            providerFromSession = sessionAttributes.get("selectedProvider")

            if providerFromSession != None:
                # Reset the provider in session in case the choice has to be made again
                print "Passport-social. prepareForStep. Setting selectedProvider from session  = '%s'" % providerFromSession
                identity.setWorkingParameter("selectedProvider", providerFromSession)
                sessionAttributes.remove("selectedProvider")
                ## SESSION_SAFE - update
                CdiUtil.bean(SessionIdService).updateSessionId(sessionId)

            loginHint = None
            if (mfaPai != None):
                entityId = sessionAttributes.get( "entityId" )
                # concatinate mfaPai and entityId
                plaintext = mfaPai + '|' + entityId
                
                randomSource = string.ascii_letters + string.digits
                loginHint = self.encryptAES( self.aesKey , plaintext )

            # This param could have been set previously in authenticate step if current step is being retried
            provider = identity.getWorkingParameter("selectedProvider")
            if provider != None:
                url = self.getPassportRedirectUrl(provider, loginHint)
                identity.setWorkingParameter("selectedProvider", None)

            elif providerParam != None:
                paramValue = sessionAttributes.get(providerParam)

                if paramValue != None:
                    print "Passport-social. prepareForStep. Found value in custom param of authorization request: %s" % paramValue
                    provider = self.getProviderFromJson(paramValue)

                    if provider == None:
                        print "Passport-social. prepareForStep. A provider value could not be extracted from custom authorization request parameter"
                    elif not provider in self.registeredProviders:
                        print "Passport-social. prepareForStep. Provider '%s' not part of known configured IDPs/OPs" % provider
                    else:
                        url = self.getPassportRedirectUrl(provider, loginHint)

            if url == None:
                print "Passport-social. prepareForStep. A page to manually select an identity provider will be shown"
            else:
                facesService = CdiUtil.bean(FacesService)
                facesService.redirectToExternalURL(url)
            
        return True
    def fillUser(self, foundUser, profile):

        for attr in profile:
            # "provider" is disregarded if part of mapping
            if attr != self.providerKey:
                values = profile[attr]
                # COLLECT - here go through existing PersistentIDs add new ones for RPs that if they are not found
                print "Passport-saml. fillUser. %s = %s" % (attr, values)
                if attr == "persistentId":
                    if (values != None):
                        # The format is rp|idp|uid, so we split by '|' and take the first element of the array
                        currentRp = StringHelper.split(values[0],'|')[0]
                        # then we look through the old values if there is a matching RP remove if from "values" and do not update
                        userPersistentIds = foundUser.getAttributeValues("persistentId")
                        if (userPersistentIds != None):
                            for userPersistentId in userPersistentIds:
                                if ( userPersistentId.find(currentRp) > -1 ):
                                    values.pop(0)

                        # if there still is a persistentId, then add it to the current user profile
                        if ( len(values) > 0):
                            print "Passport-saml. fillUser. Updating persistent IDs, original = '%s'" % userPersistentIds
                            # if there are no current Persistent IDs create a new list
                            tmpList = ArrayList(userPersistentIds) if userPersistentIds != None else ArrayList()
                            tmpList.add( values[0] )
                            print "Passport-saml. fillUser. Updating persistent IDs, updated  = '%s'" % tmpList
                            foundUser.setAttribute(attr, tmpList)
                        else:
                            print "Passport-saml. fillUser. PersistentId for RP '%s' already exists, ignoring new RP mapping" % currentRp

                elif attr == "oxExternalUid_newMfa":
                    # The attribute is here so MFA flow is REQUIRED.
                    # First we check for existing MFA PAI already in the user profile
                    mfaOxExternalUid = values[0]
                    userOxExternalUids = foundUser.getAttributeValues("oxExternalUid")
                    if (userOxExternalUids != None):
                        for userOxExternalUid in userOxExternalUids:
                            if ( userOxExternalUid.find("passport-mfa:") > -1 ):
                                # if we found an MFA PAI then remove the new value
                                mfaOxExternalUid = userOxExternalUid
                                values.pop(0)

                    # if there still is a value for MFA PAI, then add it to the current user profile because it did not exist
                    if ( len(values) > 0):
                        print "Passport-saml. fillUser. Updating MFA PAI oxExternalUid, original list = '%s'" % userOxExternalUids
                        # if there are no current Persistent IDs create a new list
                        tmpList = ArrayList(userOxExternalUids) if userOxExternalUids != None else ArrayList()
                        tmpList.add( mfaOxExternalUid )
                        print "Passport-saml. fillUser. Updating persistent IDs, updated with MFA = '%s'" % tmpList
                        foundUser.setAttribute("oxExternalUid", tmpList)
                    else:
                        print "Passport-saml. fillUser. oxExternalUid for MFA '%s' already exists, ignoring new MFA mapping" % mfaOxExternalUid

                elif attr == "mail":
                    oxtrustMails = []
                    for mail in values:
                        oxtrustMails.append('{"value":"%s","primary":false}' % mail)
                    foundUser.setAttribute("oxTrustEmail", oxtrustMails)

                else:
                    foundUser.setAttribute(attr, values)
Esempio n. 24
0
    def update(self, dynamicScopeContext, configurationAttributes):
        print "Dynamic scope [claims_scope]. Update method"

        # Get the client and session and dynamic claims
        authorizationGrant = dynamicScopeContext.getAuthorizationGrant()
        oidcClient = authorizationGrant.getClient()
        currentEntityId = "oidc:%s" % oidcClient.getClientName()
        
        # sessionDn = authorizationGrant.getSessionDn()
        # print "Dynamic scope [claims_scope]. Got session DN = '%s'" % sessionDn
        # sessionId = dynamicScopeContext.getEntryAttributeValue(sessionDn, "sessionId")
        # if ( sessionDn != None ):

        # prepare the search results attributes
        claimNamesJsonString = None
        claimsSrcJsonString = None
        
        # then we look for the SAML persistentId value in user profile
        user = dynamicScopeContext.getUser()
        userTransientIds = user.getAttributeValues("transientId")
        if ( userTransientIds != None ):
            if ( userTransientIds.size > 0 ):
                # save latest time (set to 0 initially)
                latestExpiryTimeSec = 0
                # go through existing user persistentIds
                for userTransientId in userTransientIds:
                    # if the current RP already has a mapping then skip the second phase
                    transientIdRp = StringHelper.split(userTransientId,'|')[0]
                    if ( transientIdRp == currentEntityId ):
                        print "Dynamic scope [claims_scope]. Found matching transientId '%s'" % userTransientId
                        # Format is : currentOidcRp, expiryTimeSec, userInfoUrl, accessToken
                        expiryTimeSec = StringHelper.split(userTransientId,'|')[1]
                        userInfoUrl   = StringHelper.split(userTransientId,'|')[2]
                        accessToken   = StringHelper.split(userTransientId,'|')[3]
                        # Check the last timestamp is newer than the current one and not older than 15 minutes (900 second)
                        expiryTimeSec = StringHelper.toInteger(expiryTimeSec)
                        currenttimeSec = int(round(time.time()))
                        if ( expiryTimeSec > latestExpiryTimeSec and expiryTimeSec > (currenttimeSec - 900) ):
                            # Save expiry and update/set the _claim_sources parameters
                            latestExpiryTimeSec = expiryTimeSec
                            # create a JSON object with _claim_sources for distributed claims
                            claimsSrcJsonString = '{"src1":{"endpoint":"%s","access_token":"%s"}}' % ( userInfoUrl, accessToken )
                            
                            # Set the _claim_names value to the result - static as per PCTF
                            #######################################################
                            #   "_claim_names": {
                            #     "given_name": "src1",
                            #     "family_name": "src1",
                            #     "birthdate": "src1",
                            #     "address": "src1"
                            #   },
                            # create a JSON object with _claim_sources for distributed claims
                            claimNamesJsonString = '{"given_name":"src1","family_name":"src1","birthdate":"src1","address":"src1"}'

        # set the claims if they have been found
        if ( claimNamesJsonString != None and claimsSrcJsonString != None ):
            # Get the claims object
            jsonWebResponse = dynamicScopeContext.getJsonWebResponse()
            claims = jsonWebResponse.getClaims()
            # create JSON objects
            claimNamesJson = JSONObject(claimNamesJsonString)
            claimsSrcJson = JSONObject(claimsSrcJsonString)
            # set the claims
            claims.setClaim("_claim_names", claimNamesJson)
            claims.setClaim("_claim_sources", claimsSrcJson)

        return True