示例#1
0
    def isInboundJwt(self, value):
        if value == None:
            return False

        try:

            print("passport.isInboundJwt. value = %s" % value)
            # value = value.replace("_", ".")
            # print("passport.isInboundJwt. value = %s" % value)

            jwt = Jwt.parse(value)
            print "passport.isInboundJwt. jwt = %s" % jwt

            # user_profile_json = jwt.getClaims().getClaimAsString("data")

            user_profile_json = CdiUtil.bean(EncryptionService).decrypt(
                jwt.getClaims().getClaimAsString("data"))
            print "passport.isInboundJwt. user_profile_json = %s" % user_profile_json
            if StringHelper.isEmpty(user_profile_json):
                return False
        except InvalidJwtException:
            return False

        except:
            print("Unexpected error:", sys.exc_info()[0])
            return False

        return True
    def isInboundJwt(self, value):
        if value == None:
            return False

        try:
            jwt = Jwt.parse(value)
            user_profile_json = jwt.getClaims().getClaimAsString("data")
            if StringHelper.isEmpty(user_profile_json):
                return False
        except:
            return False

        return True
    def isInboundJwt(self, value):
        if value == None:
            return False
        
        try:
            jwt = Jwt.parse(value)
            user_profile_json = jwt.getClaims().getClaimAsString("data")
            if StringHelper.isEmpty(user_profile_json):
                return False
        except:
            return False

        return True
示例#4
0
    def handleResponse(self, requestParameters):
        """Process an authentication response from passport. Returns a User object, or None in case of failure."""

        jwt = None
        externalProfile = None
        try:
            # gets jwt parameter "user" sent after authentication by passport (if exists)
            jwt_param = ServerUtil.getFirstValue(requestParameters, "user")

            # Parse JWT and validate
            # TODO: Log a security event whenever JWT validation fails
            jwt = Jwt.parse(jwt_param)
            if not self.verifySignature(jwt):
                return None
            if self.jwtHasExpired(jwt):
                return None

            claims = jwt.getClaims()
            externalProfileJson = CdiUtil.bean(EncryptionService).decrypt(
                claims.getClaimAsString("data"))
            externalProfile = json.loads(externalProfileJson)

            providerId = externalProfile["provider"]
            providerConfig = self.registeredProviders.get(providerId)
            providerType = providerConfig["type"]

            sub = claims.getClaimAsString("sub")
            if providerType == "saml":  # This is silly. It should be consistent.
                externalProfile["externalUid"] = "passport-saml:%s:%s" % (
                    providerId, sub)
            else:
                externalProfile["externalUid"] = "passport-%s:%s" % (
                    providerId, sub)

        except:
            print("Passport. handleResponse. Invalid JWT from passport")
            return None

        return externalProfile
    def authenticate(self, configurationAttributes, requestParameters, step):

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

        print "Passport. authenticate for step %s called" % str(step)
        identity = CdiUtil.bean(Identity)

        if step == 1:
            # Get JWT token
            jwt_param = ServerUtil.getFirstValue(requestParameters, "user")
            if jwt_param != None:
                print "Passport. authenticate for step 1. JWT user profile token found"

                # Parse JWT and validate
                jwt = Jwt.parse(jwt_param)
                if not self.validSignature(jwt):
                    return False

                (user_profile, json) = self.getUserProfile(jwt)
                if user_profile == None:
                    return False

                return self.attemptAuthentication(identity, user_profile, json)

            #See passportlogin.xhtml
            provider = ServerUtil.getFirstValue(requestParameters,
                                                "loginForm:provider")
            if StringHelper.isEmpty(provider):

                #it's username + passw auth
                print "Passport. authenticate for step 1. Basic authentication detected"
                logged_in = False

                credentials = identity.getCredentials()
                user_name = credentials.getUsername()
                user_password = credentials.getPassword()

                if StringHelper.isNotEmptyString(
                        user_name) and StringHelper.isNotEmptyString(
                            user_password):
                    authenticationService = CdiUtil.bean(AuthenticationService)
                    logged_in = authenticationService.authenticate(
                        user_name, user_password)

                print "Passport. authenticate for step 1. Basic authentication returned: %s" % logged_in
                return logged_in

            elif provider in self.registeredProviders:
                #it's a recognized external IDP
                identity.setWorkingParameter("selectedProvider", provider)
                print "Passport. authenticate for step 1. Retrying step 1"
                #see prepareForStep (step = 1)
                return True

        if step == 2:
            mail = ServerUtil.getFirstValue(requestParameters,
                                            "loginForm:email")
            json = identity.getWorkingParameter("passport_user_profile")

            if mail == None:
                self.setMessageError(FacesMessage.SEVERITY_ERROR,
                                     "Email was missing in user profile")
            elif json != None:
                # Completion of profile takes place
                user_profile = self.getProfileFromJson(json)
                user_profile["mail"] = mail

                return self.attemptAuthentication(identity, user_profile, json)

            print "Passport. authenticate for step 2. Failed: expected mail value in HTTP request and json profile in session"
            return False
示例#6
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        identity = CdiUtil.bean(Identity)
        userService = CdiUtil.bean(UserService)
        authenticationService = CdiUtil.bean(AuthenticationService)

        mapUserDeployment = False
        enrollUserDeployment = False
        if (configurationAttributes.containsKey("gplus_deployment_type")):
            deploymentType = StringHelper.toLowerCase(configurationAttributes.get("gplus_deployment_type").getValue2())
            
            if (StringHelper.equalsIgnoreCase(deploymentType, "map")):
                mapUserDeployment = True
            if (StringHelper.equalsIgnoreCase(deploymentType, "enroll")):
                enrollUserDeployment = True

        if (step == 1):
            print "Google+ Authenticate for step 1"
 
            gplusAuthCodeArray = requestParameters.get("gplus_auth_code")
            gplusAuthCode = gplusAuthCodeArray[0]

            # Check if user uses basic method to log in
            useBasicAuth = False
            if (StringHelper.isEmptyString(gplusAuthCode)):
                useBasicAuth = True

            # Use basic method to log in
            if (useBasicAuth):
                print "Google+ Authenticate for step 1. Basic authentication"
        
                identity.setWorkingParameter("gplus_count_login_steps", 1)
        
                credentials = identity.getCredentials()

                userName = credentials.getUsername()
                userPassword = credentials.getPassword()
        
                loggedIn = False
                if (StringHelper.isNotEmptyString(userName) and StringHelper.isNotEmptyString(userPassword)):
                    userService = CdiUtil.bean(UserService)
                    loggedIn = authenticationService.authenticate(userName, userPassword)
        
                if (not loggedIn):
                    return False
        
                return True

            # Use Google+ method to log in
            print "Google+ Authenticate for step 1. gplusAuthCode:", gplusAuthCode

            currentClientSecrets = self.getCurrentClientSecrets(self.clientSecrets, configurationAttributes, requestParameters)
            if (currentClientSecrets == None):
                print "Google+ Authenticate for step 1. Client secrets configuration is invalid"
                return False
            
            print "Google+ Authenticate for step 1. Attempting to gets tokens"
            tokenResponse = self.getTokensByCode(self.clientSecrets, configurationAttributes, gplusAuthCode)
            if ((tokenResponse == None) or (tokenResponse.getIdToken() == None) or (tokenResponse.getAccessToken() == None)):
                print "Google+ Authenticate for step 1. Failed to get tokens"
                return False
            else:
                print "Google+ Authenticate for step 1. Successfully gets tokens"

            jwt = Jwt.parse(tokenResponse.getIdToken())
            # TODO: Validate ID Token Signature  

            gplusUserUid = jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER)
            print "Google+ Authenticate for step 1. Found Google user ID in the ID token: '%s'" % gplusUserUid
            
            if (mapUserDeployment):
                # Use mapping to local IDP user
                print "Google+ Authenticate for step 1. Attempting to find user by oxExternalUid: 'gplus:%s'" % gplusUserUid

                # Check if there is user with specified gplusUserUid
                foundUser = userService.getUserByAttribute("oxExternalUid", "gplus:" + gplusUserUid)

                if (foundUser == None):
                    print "Google+ Authenticate for step 1. Failed to find user"
                    print "Google+ Authenticate for step 1. Setting count steps to 2"
                    identity.setWorkingParameter("gplus_count_login_steps", 2)
                    identity.setWorkingParameter("gplus_user_uid", gplusUserUid)
                    return True

                foundUserName = foundUser.getUserId()
                print "Google+ Authenticate for step 1. foundUserName: '******'" % foundUserName
                
                userAuthenticated = authenticationService.authenticate(foundUserName)
                if (userAuthenticated == False):
                    print "Google+ Authenticate for step 1. Failed to authenticate user"
                    return False
            
                print "Google+ Authenticate for step 1. Setting count steps to 1"
                identity.setWorkingParameter("gplus_count_login_steps", 1)

                postLoginResult = self.extensionPostLogin(configurationAttributes, foundUser)
                print "Google+ Authenticate for step 1. postLoginResult: '%s'" % postLoginResult

                return postLoginResult
            elif (enrollUserDeployment):
                # Use auto enrollment to local IDP
                print "Google+ Authenticate for step 1. Attempting to find user by oxExternalUid: 'gplus:%s'" % gplusUserUid
 
                # Check if there is user with specified gplusUserUid
                foundUser = userService.getUserByAttribute("oxExternalUid", "gplus:" + gplusUserUid)
 
                if (foundUser == None):
                    # Auto user enrollemnt
                    print "Google+ Authenticate for step 1. There is no user in LDAP. Adding user to local LDAP"

                    print "Google+ Authenticate for step 1. Attempting to gets user info"
                    userInfoResponse = self.getUserInfo(currentClientSecrets, configurationAttributes, tokenResponse.getAccessToken())
                    if ((userInfoResponse == None) or (userInfoResponse.getClaims().size() == 0)):
                        print "Google+ Authenticate for step 1. Failed to get user info"
                        return False
                    else:
                        print "Google+ Authenticate for step 1. Successfully gets user info"
                    
                    gplusResponseAttributes = userInfoResponse.getClaims()
 
                    # Convert Google+ user claims to lover case
                    gplusResponseNormalizedAttributes = HashMap()
                    for gplusResponseAttributeEntry in gplusResponseAttributes.entrySet():
                        gplusResponseNormalizedAttributes.put(
                            StringHelper.toLowerCase(gplusResponseAttributeEntry.getKey()), gplusResponseAttributeEntry.getValue())
 
                    currentAttributesMapping = self.getCurrentAttributesMapping(self.attributesMapping, configurationAttributes, requestParameters)
                    print "Google+ Authenticate for step 1. Using next attributes mapping '%s'" % currentAttributesMapping
 
                    newUser = User()
                    for attributesMappingEntry in currentAttributesMapping.entrySet():
                        remoteAttribute = attributesMappingEntry.getKey()
                        localAttribute = attributesMappingEntry.getValue()
 
                        localAttributeValue = gplusResponseNormalizedAttributes.get(remoteAttribute)
                        if (localAttribute != None):
                            newUser.setAttribute(localAttribute, localAttributeValue)
 
                    if (newUser.getAttribute("sn") == None):
                        newUser.setAttribute("sn", gplusUserUid)
 
                    if (newUser.getAttribute("cn") == None):
                        newUser.setAttribute("cn", gplusUserUid)

                    # Add mail to oxTrustEmail so that the user's
                    # email is available through the SCIM interface
                    # too.
                    if (newUser.getAttribute("oxTrustEmail") is None and
                        newUser.getAttribute("mail") is not None):
                        oxTrustEmail = {
                            "value": newUser.getAttribute("mail"),
                            "display": newUser.getAttribute("mail"),
                            "primary": True,
                            "operation": None,
                            "reference": None,
                            "type": "other"
                        }
                        newUser.setAttribute("oxTrustEmail", json.dumps(oxTrustEmail))

                    newUser.setAttribute("oxExternalUid", "gplus:" + gplusUserUid)
                    print "Google+ Authenticate for step 1. Attempting to add user '%s' with next attributes '%s'" % (gplusUserUid, newUser.getCustomAttributes())
 
                    foundUser = userService.addUser(newUser, True)
                    print "Google+ Authenticate for step 1. Added new user with UID: '%s'" % foundUser.getUserId()

                foundUserName = foundUser.getUserId()
                print "Google+ Authenticate for step 1. foundUserName: '******'" % foundUserName

                userAuthenticated = authenticationService.authenticate(foundUserName)
                if (userAuthenticated == False):
                    print "Google+ Authenticate for step 1. Failed to authenticate user"
                    return False

                print "Google+ Authenticate for step 1. Setting count steps to 1"
                identity.setWorkingParameter("gplus_count_login_steps", 1)

                print "Google+ Authenticate for step 1. Attempting to run extension postLogin"
                postLoginResult = self.extensionPostLogin(configurationAttributes, foundUser)
                print "Google+ Authenticate for step 1. postLoginResult: '%s'" % postLoginResult

                return postLoginResult
            else:
                # Check if there is user with specified gplusUserUid
                print "Google+ Authenticate for step 1. Attempting to find user by uid: '%s'" % gplusUserUid

                foundUser = userService.getUser(gplusUserUid)
                if (foundUser == None):
                    print "Google+ Authenticate for step 1. Failed to find user"
                    return False

                foundUserName = foundUser.getUserId()
                print "Google+ Authenticate for step 1. foundUserName: '******'" % foundUserName

                userAuthenticated = authenticationService.authenticate(foundUserName)
                if (userAuthenticated == False):
                    print "Google+ Authenticate for step 1. Failed to authenticate user"
                    return False

                print "Google+ Authenticate for step 1. Setting count steps to 1"
                identity.setWorkingParameter("gplus_count_login_steps", 1)

                postLoginResult = self.extensionPostLogin(configurationAttributes, foundUser)
                print "Google+ Authenticate for step 1. postLoginResult: '%s'" % postLoginResult

                return postLoginResult
        elif (step == 2):
            print "Google+ Authenticate for step 2"
            
            sessionAttributes = identity.getSessionId().getSessionAttributes()
            if (sessionAttributes == None) or not sessionAttributes.containsKey("gplus_user_uid"):
                print "Google+ Authenticate for step 2. gplus_user_uid is empty"
                return False

            gplusUserUid = sessionAttributes.get("gplus_user_uid")
            passed_step1 = StringHelper.isNotEmptyString(gplusUserUid)
            if (not passed_step1):
                return False

            identity = CdiUtil.bean(Identity)
            credentials = identity.getCredentials()

            userName = credentials.getUsername()
            userPassword = credentials.getPassword()

            loggedIn = False
            if (StringHelper.isNotEmptyString(userName) and StringHelper.isNotEmptyString(userPassword)):
                loggedIn = authenticationService.authenticate(userName, userPassword)

            if (not loggedIn):
                return False

            # Check if there is user which has gplusUserUid
            # Avoid mapping Google account to more than one IDP account
            foundUser = userService.getUserByAttribute("oxExternalUid", "gplus:" + gplusUserUid)

            if (foundUser == None):
                # Add gplusUserUid to user one id UIDs
                foundUser = userService.addUserAttribute(userName, "oxExternalUid", "gplus:" + gplusUserUid)
                if (foundUser == None):
                    print "Google+ Authenticate for step 2. Failed to update current user"
                    return False

                postLoginResult = self.extensionPostLogin(configurationAttributes, foundUser)
                print "Google+ Authenticate for step 2. postLoginResult: '%s'" % postLoginResult

                return postLoginResult
            else:
                foundUserName = foundUser.getUserId()
                print "Google+ Authenticate for step 2. foundUserName: '******'" % foundUserName
    
                if StringHelper.equals(userName, foundUserName):
                    postLoginResult = self.extensionPostLogin(configurationAttributes, foundUser)
                    print "Google+ Authenticate for step 2. postLoginResult: '%s'" % postLoginResult
    
                    return postLoginResult
        
            return False
        else:
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):

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

        print "Passport. authenticate for step %s called" % str(step)
        identity = CdiUtil.bean(Identity)

        if step == 1:
            jwt_param = None

            if self.isInboundFlow(identity):
                # if is idp-initiated inbound flow
                print "Passport. authenticate for step 1. Detected idp-initiated inbound Saml flow"
                # get request from session attributes
                jwt_param = identity.getSessionId().getSessionAttributes().get(AuthorizeRequestParam.STATE)
                # now jwt_param != None



            if jwt_param == None:
                # gets jwt parameter "user" sent after authentication by passport (if exists)
                jwt_param = ServerUtil.getFirstValue(requestParameters, "user")


            if jwt_param != None:
                # and now that the jwt_param user exists...
                
                print "Passport. authenticate for step 1. JWT user profile token found"

                # Parse JWT and validate
                jwt = Jwt.parse(jwt_param)
                
                if not self.validSignature(jwt):
                    return False

                if self.jwtHasExpired(jwt):
                    return False

                # Gets user profile as string and json using the information on JWT
                (user_profile, jsonp) = self.getUserProfile(jwt)

                if user_profile == None:
                    return False

                return self.attemptAuthentication(identity, user_profile, jsonp)

            #See passportlogin.xhtml
            provider = ServerUtil.getFirstValue(requestParameters, "loginForm:provider")
            if StringHelper.isEmpty(provider):

                #it's username + passw auth
                print "Passport. authenticate for step 1. Basic authentication detected"
                logged_in = False

                credentials = identity.getCredentials()
                user_name = credentials.getUsername()
                user_password = credentials.getPassword()

                if StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password):
                    authenticationService = CdiUtil.bean(AuthenticationService)
                    logged_in = authenticationService.authenticate(user_name, user_password)

                print "Passport. authenticate for step 1. Basic authentication returned: %s" % logged_in
                return logged_in


            elif provider in self.registeredProviders:
                # user selected provider
                # it's a recognized external IDP

                identity.setWorkingParameter("selectedProvider", provider)
                print "Passport. authenticate for step 1. Retrying step 1"

                #see prepareForStep (step = 1)
                return True

        if step == 2:
            mail = ServerUtil.getFirstValue(requestParameters, "loginForm:email")
            jsonp = identity.getWorkingParameter("passport_user_profile")

            if mail == None:
                self.setMessageError(FacesMessage.SEVERITY_ERROR, "Email was missing in user profile")
            elif jsonp != None:
                # Completion of profile takes place
                user_profile = json.loads(jsonp)
                user_profile["mail"] = [ mail ]

                return self.attemptAuthentication(identity, user_profile, jsonp)

            print "Passport. authenticate for step 2. Failed: expected mail value in HTTP request and json profile in session"
            return False
示例#8
0
 def modifyResponse(self, responseAsJsonObject, context):
     print "Inside modifyResponse method of introspection script ..."
     try:
         # Getting user-info-jwt
         ujwt = context.getHttpRequest().getParameter("ujwt")
         print ujwt
         if not ujwt:
             print "UJWT is empty or null"
         # Parse jwt
         userInfoJwt = Jwt.parse(ujwt)
         # Get auth-server keys
         url = URL("https://gasmyr.gluu.org/jans-auth/restv1/jwks")
         conn = url.openConnection()
         conn.setDoOutput(True)
         conn.setRequestMethod("GET")
         conn.setRequestProperty("Content-type", "application/json")
         if conn.getResponseCode() != 200: 
             print "Failed!!"
             print conn.getResponseCode()
             print conn.getResponseMessage()
         else:
             print "Success!! Able to connect for auth-server jwks"
             print conn.getResponseCode()
             print conn.getResponseMessage()
         
         instr = conn.getInputStream()
         instrreader = InputStreamReader(instr)
         breader = BufferedReader(instrreader)
         output = breader.readLine()
         jsonResult = ""
         while output != None:
             if output != None:
                 jsonResult += output
             output = breader.readLine()
         # JWKS
         jwks = JSONObject(jsonResult)
         conn.disconnect()
         
         # Validate JWT
         authCryptoProvider = OxAuthCryptoProvider()
         validJwt = authCryptoProvider.verifySignature(userInfoJwt.getSigningInput(), userInfoJwt.getEncodedSignature(), userInfoJwt.getHeader().getKeyId(), jwks, None, userInfoJwt.getHeader().getSignatureAlgorithm())
         print validJwt       
         
         if validJwt == True:
             print "user-info jwt is valid"
             # Get claims from parsed JWT
             jwtClaims = userInfoJwt.getClaims()
             jansAdminUIRole = jwtClaims.getClaim("jansAdminUIRole")
             print jansAdminUIRole.getString(0)
             # role-scope mapping
             scope = []
             if jansAdminUIRole.getString(0) == 'api-viewer':
                 scope.append("https://jans.io/oauth/config/attributes.readonly")
                 scope.append("https://jans.io/oauth/config/acrs.readonly")
                 scope.append("https://jans.io/oauth/config/scopes.readonly")
                 scope.append("https://jans.io/oauth/config/scripts.readonly")
                 scope.append("https://jans.io/oauth/config/openid/clients.readonly")
                 scope.append("https://jans.io/oauth/config/smtp.readonly")
                 scope.append("https://jans.io/oauth/config/logging.readonly")
                 scope.append("https://jans.io/oauth/config/uma/resources.readonly")
                 scope.append("https://jans.io/oauth/config/database/ldap.readonly")
                 scope.append("https://jans.io/oauth/config/jwks.readonly")
                 scope.append("https://jans.io/oauth/config/fido2.readonly")
                 scope.append("https://jans.io/oauth/config/cache.readonly")
                 scope.append("https://jans.io/oauth/jans-auth-server/config/properties.readonly")
                 scope.append("https://jans.io/oauth/config/database/couchbase.readonly")
             elif jansAdminUIRole.getString(0) == 'api-editor':
                 scope.append("https://jans.io/oauth/config/attributes.readonly")
                 scope.append("https://jans.io/oauth/config/attributes.write")
                 scope.append("https://jans.io/oauth/config/acrs.readonly")
                 scope.append("https://jans.io/oauth/config/acrs.write")
                 scope.append("https://jans.io/oauth/config/scopes.readonly")
                 scope.append("https://jans.io/oauth/config/scopes.write")
                 scope.append("https://jans.io/oauth/config/scripts.readonly")
                 scope.append("https://jans.io/oauth/config/scripts.write")
                 scope.append("https://jans.io/oauth/config/openid/clients.readonly")
                 scope.append("https://jans.io/oauth/config/openid/clients.write")
                 scope.append("https://jans.io/oauth/config/smtp.readonly")
                 scope.append("https://jans.io/oauth/config/smtp.write")
                 scope.append("https://jans.io/oauth/config/logging.readonly")
                 scope.append("https://jans.io/oauth/config/logging.write")
                 scope.append("https://jans.io/oauth/config/uma/resources.readonly")
                 scope.append("https://jans.io/oauth/config/uma/resources.write")
                 scope.append("https://jans.io/oauth/config/database/ldap.readonly")
                 scope.append("https://jans.io/oauth/config/database/ldap.write")
                 scope.append("https://jans.io/oauth/config/jwks.readonly")
                 scope.append("https://jans.io/oauth/config/jwks.write")
                 scope.append("https://jans.io/oauth/config/fido2.readonly")
                 scope.append("https://jans.io/oauth/config/fido2.write")
                 scope.append("https://jans.io/oauth/config/cache.readonly")
                 scope.append("https://jans.io/oauth/config/cache.write")
                 scope.append("https://jans.io/oauth/config/database/couchbase.readonly")
                 scope.append("https://jans.io/oauth/config/database/couchbase.write")
                 scope.append("https://jans.io/oauth/jans-auth-server/config/properties.readonly")
             elif jansAdminUIRole.getString(0) == 'api-manager':
                 scope.append("https://jans.io/oauth/config/attributes.readonly")
                 scope.append("https://jans.io/oauth/config/attributes.write")
                 scope.append("https://jans.io/oauth/config/attributes.delete")
                 scope.append("https://jans.io/oauth/config/acrs.readonly")
                 scope.append("https://jans.io/oauth/config/acrs.write")
                 scope.append("https://jans.io/oauth/config/acrs.delete")
                 scope.append("https://jans.io/oauth/config/scopes.readonly")
                 scope.append("https://jans.io/oauth/config/scopes.write")
                 scope.append("https://jans.io/oauth/config/scopes.delete")
                 scope.append("https://jans.io/oauth/config/scripts.readonly")
                 scope.append("https://jans.io/oauth/config/scripts.write")
                 scope.append("https://jans.io/oauth/config/scripts.delete")
                 scope.append("https://jans.io/oauth/config/openid/clients.readonly")
                 scope.append("https://jans.io/oauth/config/openid/clients.write")
                 scope.append("https://jans.io/oauth/config/openid/clients.delete")
                 scope.append("https://jans.io/oauth/config/smtp.readonly")
                 scope.append("https://jans.io/oauth/config/smtp.write")
                 scope.append("https://jans.io/oauth/config/smtp.delete")
                 scope.append("https://jans.io/oauth/config/logging.readonly")
                 scope.append("https://jans.io/oauth/config/logging.write")
                 scope.append("https://jans.io/oauth/config/uma/resources.readonly")
                 scope.append("https://jans.io/oauth/config/uma/resources.write")
                 scope.append("https://jans.io/oauth/config/uma/resources.delete")
                 scope.append("https://jans.io/oauth/config/database/ldap.readonly")
                 scope.append("https://jans.io/oauth/config/database/ldap.write")
                 scope.append("https://jans.io/oauth/config/database/ldap.delete")
                 scope.append("https://jans.io/oauth/config/jwks.readonly")
                 scope.append("https://jans.io/oauth/config/jwks.write")
                 scope.append("https://jans.io/oauth/config/fido2.readonly")
                 scope.append("https://jans.io/oauth/config/fido2.write")
                 scope.append("https://jans.io/oauth/config/cache.readonly")
                 scope.append("https://jans.io/oauth/config/cache.write")
                 scope.append("https://jans.io/oauth/config/database/couchbase.readonly")
                 scope.append("https://jans.io/oauth/config/database/couchbase.write")
                 scope.append("https://jans.io/oauth/jans-auth-server/config/properties.readonly")
             elif jansAdminUIRole.getString(0) == 'api-admin':
                 scope.append("https://jans.io/oauth/config/attributes.readonly")
                 scope.append("https://jans.io/oauth/config/attributes.write")
                 scope.append("https://jans.io/oauth/config/attributes.delete")
                 scope.append("https://jans.io/oauth/config/acrs.readonly")
                 scope.append("https://jans.io/oauth/config/acrs.write")
                 scope.append("https://jans.io/oauth/config/acrs.delete")
                 scope.append("https://jans.io/oauth/config/scopes.readonly")
                 scope.append("https://jans.io/oauth/config/scopes.write")
                 scope.append("https://jans.io/oauth/config/scopes.delete")
                 scope.append("https://jans.io/oauth/config/scripts.readonly")
                 scope.append("https://jans.io/oauth/config/scripts.write")
                 scope.append("https://jans.io/oauth/config/scripts.delete")
                 scope.append("https://jans.io/oauth/config/openid/clients.readonly")
                 scope.append("https://jans.io/oauth/config/openid/clients.write")
                 scope.append("https://jans.io/oauth/config/openid/clients.delete")
                 scope.append("https://jans.io/oauth/config/smtp.readonly")
                 scope.append("https://jans.io/oauth/config/smtp.write")
                 scope.append("https://jans.io/oauth/config/smtp.delete")
                 scope.append("https://jans.io/oauth/config/logging.readonly")
                 scope.append("https://jans.io/oauth/config/logging.write")
                 scope.append("https://jans.io/oauth/config/uma/resources.readonly")
                 scope.append("https://jans.io/oauth/config/uma/resources.write")
                 scope.append("https://jans.io/oauth/config/uma/resources.delete")
                 scope.append("https://jans.io/oauth/config/database/ldap.readonly")
                 scope.append("https://jans.io/oauth/config/database/ldap.write")
                 scope.append("https://jans.io/oauth/config/database/ldap.delete")
                 scope.append("https://jans.io/oauth/config/jwks.readonly")
                 scope.append("https://jans.io/oauth/config/jwks.write")
                 scope.append("https://jans.io/oauth/config/fido2.readonly")
                 scope.append("https://jans.io/oauth/config/fido2.write")
                 scope.append("https://jans.io/oauth/config/cache.readonly")
                 scope.append("https://jans.io/oauth/config/cache.write")
                 scope.append("https://jans.io/oauth/config/database/couchbase.readonly")
                 scope.append("https://jans.io/oauth/config/database/couchbase.write")
                 scope.append("https://jans.io/oauth/jans-auth-server/config/properties.write")
                 scope.append("https://jans.io/oauth/jans-auth-server/config/properties.readonly")
         responseAsJsonObject.accumulate("scope", scope)
     except Exception as e:
             print "Exception occured. Unable to resolve role/scope mapping."
             print e
     return True
    def authenticate(self, configurationAttributes, requestParameters, step):

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

        print "Passport. authenticate for step %s called" % str(step)
        identity = CdiUtil.bean(Identity)

        if step == 1:
            # Get JWT token
            jwt_param = ServerUtil.getFirstValue(requestParameters, "user")
            if jwt_param != None:
                print "Passport. authenticate for step 1. JWT user profile token found"

                # Parse JWT and validate
                jwt = Jwt.parse(jwt_param)
                if not self.validSignature(jwt):
                    return False

                (user_profile, json) = self.getUserProfile(jwt)
                if user_profile == None:
                    return False

                return self.attemptAuthentication(identity, user_profile, json)

            #See passportlogin.xhtml
            provider = ServerUtil.getFirstValue(requestParameters, "loginForm:provider")
            if StringHelper.isEmpty(provider):

                #it's username + passw auth
                print "Passport. authenticate for step 1. Basic authentication detected"
                logged_in = False

                credentials = identity.getCredentials()
                user_name = credentials.getUsername()
                user_password = credentials.getPassword()

                if StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password):
                    authenticationService = CdiUtil.bean(AuthenticationService)
                    logged_in = authenticationService.authenticate(user_name, user_password)

                print "Passport. authenticate for step 1. Basic authentication returned: %s" % logged_in
                return logged_in

            elif provider in self.registeredProviders:
                #it's a recognized external IDP
                identity.setWorkingParameter("selectedProvider", provider)
                print "Passport. authenticate for step 1. Retrying step 1"
                #see prepareForStep (step = 1)
                return True

        if step == 2:
            mail = ServerUtil.getFirstValue(requestParameters, "loginForm:email")
            json = identity.getWorkingParameter("passport_user_profile")

            if mail == None:
                self.setEmailMessageError()
            elif json != None:
                # Completion of profile takes place
                user_profile = self.getProfileFromJson(json)
                user_profile["mail"] = mail

                return self.attemptAuthentication(identity, user_profile, json)

            print "Passport. authenticate for step 2. Failed: expected mail value in HTTP request and json profile in session"
            return False