def isValidAuthenticationMethod(self, usageType, configurationAttributes):
        print "CAS2 Rest API authenticate isValidAuthenticationMethod"
        cas_validation_uri = configurationAttributes.get("cas_validation_uri").getValue2()
        cas_validation_pattern = configurationAttributes.get("cas_validation_pattern").getValue2()
        cas_validation_timeout = int(configurationAttributes.get("cas_validation_timeout").getValue2()) * 1000

        httpService = HttpService.instance();

        http_client = httpService.getHttpsClientTrustAll();
        http_client_params = http_client.getParams();
        http_client_params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, cas_validation_timeout);

        try:
            http_response = httpService.executeGet(http_client, cas_validation_uri)
        except:
            print "CAS2 Rest API authenticate isValidAuthenticationMethod. Exception: ", sys.exc_info()[1]
            return False

        if (http_response.getStatusLine().getStatusCode() != 200):
            print "CAS2 Rest API authenticate isValidAuthenticationMethod. Get invalid response from CAS2 server: ", str(http_response_ticket.getStatusLine().getStatusCode())
            httpService.consume(http_response)
            return False

        validation_response_bytes = httpService.getResponseContent(http_response)
        validation_response_string = httpService.convertEntityToString(validation_response_bytes)
        httpService.consume(http_response)

        if (validation_response_string == None or validation_response_string.find(cas_validation_pattern) == -1):
            print "CAS2 Rest API authenticate isValidAuthenticationMethod. Get invalid login page from CAS2 server:"
            return False

        return True
Beispiel #2
0
    def init(self, configurationAttributes):
        print "InWebo. Initialization"

        iw_cert_store_type = configurationAttributes.get(
            "iw_cert_store_type").getValue2()
        iw_cert_path = configurationAttributes.get("iw_cert_path").getValue2()
        iw_creds_file = configurationAttributes.get(
            "iw_creds_file").getValue2()

        # Load credentials from file
        f = open(iw_creds_file, 'r')
        try:
            creds = json.loads(f.read())
        except:
            return False
        finally:
            f.close()

        iw_cert_password = creds["CERT_PASSWORD"]
        try:
            stringEncrypter = StringEncrypter.defaultInstance()
            iw_cert_password = stringEncrypter.decrypt(iw_cert_password)
        except:
            return False

        httpService = HttpService.instance()
        self.client = httpService.getHttpsClient(None, None, None,
                                                 iw_cert_store_type,
                                                 iw_cert_path,
                                                 iw_cert_password)
        print "InWebo. Initialized successfully"

        return True
    def validateInweboToken(self, iw_api_uri, iw_service_id, user_name, iw_token):
        httpService = HttpService.instance()
        xmlService = XmlService.instance();

        if StringHelper.isEmpty(iw_token):
            print "InWebo. Token verification. iw_token is empty"
            return False

        request_uri = iw_api_uri + "?action=authenticate" + "&serviceId=" + httpService.encodeUrl(iw_service_id) + "&userId=" + httpService.encodeUrl(user_name) + "&token=" + httpService.encodeUrl(iw_token)
        print "InWebo. Token verification. Attempting to send authentication request:", request_uri
        # Execute request
        http_response = httpService.executeGet(self.client, request_uri)
            
        # Validate response code
        response_validation = httpService.isResponseStastusCodeOk(http_response)
        if response_validation == False:
            print "InWebo. Token verification. Get unsuccessful response code"
            return False

        authentication_response_bytes = httpService.getResponseContent(http_response)
        print "InWebo. Token verification. Get response:", httpService.convertEntityToString(authentication_response_bytes)

        # Validate authentication response
        response_validation = httpService.isContentTypeXml(http_response)
        if response_validation == False:
            print "InWebo. Token verification. Get invalid response"
            return False
        
        # Parse XML response
        try:
            xmlDocument = xmlService.getXmlDocument(authentication_response_bytes)
        except Exception, err:
            print "InWebo. Token verification. Failed to parse XML response:", err
            return False
    def executePost(self, request_uri, request_data):
        httpService = HttpService.instance()

        request_headers = { "Content-type" : "application/json; charset=UTF-8", "Accept" : "application/json" }

        try:
            http_service_response = httpService.executePost(self.http_client, request_uri, None, request_headers, request_data)
            http_response = http_service_response.getHttpResponse()
        except:
            print "UAF. Validate POST response. Exception: ", sys.exc_info()[1]
            return None

        try:
            if not httpService.isResponseStastusCodeOk(http_response):
                print "UAF. Validate POST response. Get invalid response from  server: %s" % str(http_response.getStatusLine().getStatusCode())
                httpService.consume(http_response)
                return None
    
            response_bytes = httpService.getResponseContent(http_response)
            response_string = httpService.convertEntityToString(response_bytes)
            httpService.consume(http_response)
            
            return response_string
        finally:
            http_service_response.closeConnection()
        return None
Beispiel #5
0
    def executePost(self, request_uri, request_data):
        httpService = HttpService.instance()

        request_headers = {
            "Content-type": "application/json; charset=UTF-8",
            "Accept": "application/json"
        }

        try:
            http_service_response = httpService.executePost(
                self.http_client, request_uri, None, request_headers,
                request_data)
            http_response = http_service_response.getHttpResponse()
        except:
            print "UAF. Validate POST response. Exception: ", sys.exc_info()[1]
            return None

        try:
            if not httpService.isResponseStastusCodeOk(http_response):
                print "UAF. Validate POST response. Get invalid response from  server: %s" % str(
                    http_response.getStatusLine().getStatusCode())
                httpService.consume(http_response)
                return None

            response_bytes = httpService.getResponseContent(http_response)
            response_string = httpService.convertEntityToString(response_bytes)
            httpService.consume(http_response)

            return response_string
        finally:
            http_service_response.closeConnection()
        return None
    def init(self, configurationAttributes):
        print "InWebo. Initialization"

        iw_cert_store_type = configurationAttributes.get("iw_cert_store_type").getValue2()
        iw_cert_path = configurationAttributes.get("iw_cert_path").getValue2()
        iw_creds_file = configurationAttributes.get("iw_creds_file").getValue2()

        # Load credentials from file
        f = open(iw_creds_file, 'r')
        try:
            creds = json.loads(f.read())
        except:
            return False
        finally:
            f.close()

        iw_cert_password = creds["CERT_PASSWORD"]
        try:
            stringEncrypter = StringEncrypter.defaultInstance()
            iw_cert_password = stringEncrypter.decrypt(iw_cert_password)
        except:
            return False

        httpService = HttpService.instance()
        self.client = httpService.getHttpsClient(None, None, None, iw_cert_store_type, iw_cert_path, iw_cert_password)
        print "InWebo. Initialized successfully"

        return True   
Beispiel #7
0
    def prepareForStep(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        authenticationService = AuthenticationService.instance()

        if (step == 1):
            print "Saml. Prepare for step 1"
            
            httpService = HttpService.instance()
            request = FacesContext.getCurrentInstance().getExternalContext().getRequest()
            assertionConsumerServiceUrl = httpService.constructServerUrl(request) + "/postlogin"
            print "Saml. Prepare for step 1. Prepared assertionConsumerServiceUrl: '%s'" % assertionConsumerServiceUrl
            
            currentSamlConfiguration = self.getCurrentSamlConfiguration(self.samlConfiguration, configurationAttributes, requestParameters)
            if (currentSamlConfiguration == None):
                print "Saml. Prepare for step 1. Client saml configuration is invalid"
                return False

            # Generate an AuthRequest and send it to the identity provider
            samlAuthRequest = AuthRequest(currentSamlConfiguration)
            external_auth_request_uri = currentSamlConfiguration.getIdpSsoTargetUrl() + "?SAMLRequest=" + samlAuthRequest.getRequest(True, assertionConsumerServiceUrl)

            print "Saml. Prepare for step 1. external_auth_request_uri: '%s'" % external_auth_request_uri
            
            context.set("external_auth_request_uri", external_auth_request_uri)

            return True
        elif (step == 2):
            print "Saml. Prepare for step 2"

            return True
        else:
            return False
    def init(self, configurationAttributes):
        print "UAF. Initialization"

        if not configurationAttributes.containsKey("uaf_server_uri"):
            print "UAF. Initialization. Property uaf_server_uri is mandatory"
            return False

        self.uaf_server_uri = configurationAttributes.get("uaf_server_uri").getValue2()

        self.uaf_policy_name = "default"
        if configurationAttributes.containsKey("uaf_policy_name"):
            self.uaf_policy_name = configurationAttributes.get("uaf_policy_name").getValue2()

        self.send_push_notifaction = False
        if configurationAttributes.containsKey("send_push_notifaction"):
            self.send_push_notifaction = StringHelper.toBoolean(configurationAttributes.get("send_push_notifaction").getValue2(), False)

        self.registration_uri = None
        if configurationAttributes.containsKey("registration_uri"):
            self.registration_uri = configurationAttributes.get("registration_uri").getValue2()

        self.customQrOptions = {}
        if configurationAttributes.containsKey("qr_options"):
            self.customQrOptions = configurationAttributes.get("qr_options").getValue2()

        print "UAF. Initializing HTTP client"
        httpService = HttpService.instance()
        self.http_client = httpService.getHttpsClient()
        http_client_params = self.http_client.getParams()
        http_client_params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15 * 1000)

        print "UAF. Initialized successfully. uaf_server_uri: '%s', uaf_policy_name: '%s', send_push_notifaction: '%s', registration_uri: '%s', qr_options: '%s'" % (self.uaf_server_uri, self.uaf_policy_name, self.send_push_notifaction, self.registration_uri, self.customQrOptions)
        
        print "UAF. Initialized successfully"
        return True
    def prepareForStep(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        authenticationService = AuthenticationService.instance()

        if (step == 1):
            print "Saml. Prepare for step 1"
            
            httpService = HttpService.instance();
            request = FacesContext.getCurrentInstance().getExternalContext().getRequest()
            assertionConsumerServiceUrl = httpService.constructServerUrl(request) + "/postlogin"
            print "Saml. Prepare for step 1. Prepared assertionConsumerServiceUrl:", assertionConsumerServiceUrl
            
            currentSamlConfiguration = self.getCurrentSamlConfiguration(self.samlConfiguration, configurationAttributes, requestParameters)
            if (currentSamlConfiguration == None):
                print "Saml. Prepare for step 1. Client saml configuration is invalid"
                return False

            # Generate an AuthRequest and send it to the identity provider
            samlAuthRequest = AuthRequest(currentSamlConfiguration)
            external_auth_request_uri = currentSamlConfiguration.getIdpSsoTargetUrl() + "?SAMLRequest=" + samlAuthRequest.getRequest(True, assertionConsumerServiceUrl)

            print "Saml. Prepare for step 1. external_auth_request_uri:", external_auth_request_uri
            
            context.set("external_auth_request_uri", external_auth_request_uri)

            return True
        elif (step == 2):
            print "Saml. Prepare for step 2"

            return True
        else:
            return False
    def isValidAuthenticationMethod(self, usageType, configurationAttributes):
        print "CAS2. Rest API authenticate isValidAuthenticationMethod"

        if (not (configurationAttributes.containsKey("cas_validation_uri") and
                 configurationAttributes.containsKey("cas_validation_pattern")
                 and configurationAttributes.containsKey(
                     "cas_validation_timeout"))):
            return True

        cas_validation_uri = configurationAttributes.get(
            "cas_validation_uri").getValue2()
        cas_validation_pattern = configurationAttributes.get(
            "cas_validation_pattern").getValue2()
        cas_validation_timeout = int(
            configurationAttributes.get(
                "cas_validation_timeout").getValue2()) * 1000

        httpService = HttpService.instance()

        http_client = httpService.getHttpsClient()
        http_client_params = http_client.getParams()
        http_client_params.setIntParameter(
            CoreConnectionPNames.CONNECTION_TIMEOUT, cas_validation_timeout)

        try:
            http_service_response = httpService.executeGet(
                http_client, cas_validation_uri)
            http_response = http_service_response.getHttpResponse()
        except:
            print "CAS2. Rest API authenticate isValidAuthenticationMethod. Exception: ", sys.exc_info(
            )[1]
            return False

        try:
            if (http_response.getStatusLine().getStatusCode() != 200):
                print "CAS2. Rest API authenticate isValidAuthenticationMethod. Get invalid response from CAS2 server: ", str(
                    http_response_ticket.getStatusLine().getStatusCode())
                httpService.consume(http_response)
                return False

            validation_response_bytes = httpService.getResponseContent(
                http_response)
            validation_response_string = httpService.convertEntityToString(
                validation_response_bytes)
            httpService.consume(http_response)
        finally:
            http_service_response.closeConnection()

        if (validation_response_string == None or
                validation_response_string.find(cas_validation_pattern) == -1):
            print "CAS2. Rest API authenticate isValidAuthenticationMethod. Get invalid login page from CAS2 server:"
            return False

        return True
Beispiel #11
0
    def init(self, configurationAttributes):
        print "UAF. Initialization"

        if not configurationAttributes.containsKey("uaf_server_uri"):
            print "UAF. Initialization. Property uaf_server_uri is mandatory"
            return False

        self.uaf_server_uri = configurationAttributes.get(
            "uaf_server_uri").getValue2()

        self.uaf_policy_name = "default"
        if configurationAttributes.containsKey("uaf_policy_name"):
            self.uaf_policy_name = configurationAttributes.get(
                "uaf_policy_name").getValue2()

        self.send_push_notifaction = False
        if configurationAttributes.containsKey("send_push_notifaction"):
            self.send_push_notifaction = StringHelper.toBoolean(
                configurationAttributes.get(
                    "send_push_notifaction").getValue2(), False)

        self.registration_uri = None
        if configurationAttributes.containsKey("registration_uri"):
            self.registration_uri = configurationAttributes.get(
                "registration_uri").getValue2()

        self.customQrOptions = {}
        if configurationAttributes.containsKey("qr_options"):
            self.customQrOptions = configurationAttributes.get(
                "qr_options").getValue2()

        print "UAF. Initializing HTTP client"
        httpService = HttpService.instance()
        self.http_client = httpService.getHttpsClient()
        http_client_params = self.http_client.getParams()
        http_client_params.setIntParameter(
            CoreConnectionPNames.CONNECTION_TIMEOUT, 15 * 1000)

        print "UAF. Initialized successfully. uaf_server_uri: '%s', uaf_policy_name: '%s', send_push_notifaction: '%s', registration_uri: '%s', qr_options: '%s'" % (
            self.uaf_server_uri, self.uaf_policy_name,
            self.send_push_notifaction, self.registration_uri,
            self.customQrOptions)

        print "UAF. Initialized successfully"
        return True
    def validateRecaptcha(self, recaptcha_response):
        print "Cert. Validate recaptcha response"

        request = FacesContext.getCurrentInstance().getExternalContext().getRequest()
        remoteip = request.getHeader("X-FORWARDED-FOR")
        if remoteip == None:
            remoteip = request.getRemoteAddr()
        print "Cert. Validate recaptcha response. remoteip: '%s'" % remoteip

        httpService = HttpService.instance();

        http_client = httpService.getHttpsClient();
        http_client_params = http_client.getParams();
        http_client_params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15 * 1000);
        
        recaptcha_validation_url = "https://www.google.com/recaptcha/api/siteverify"
        recaptcha_validation_request = urllib.urlencode({ "secret" : self.recaptcha_creds['secret_key'], "response" : recaptcha_response, "remoteip" : remoteip })
        recaptcha_validation_headers = { "Content-type" : "application/x-www-form-urlencoded", "Accept" : "application/json" }

        try:
            http_service_response = httpService.executePost(http_client, recaptcha_validation_url, None, recaptcha_validation_headers, recaptcha_validation_request)
            http_response = http_service_response.getHttpResponse()
        except:
            print "Cert. Validate recaptcha response. Exception: ", sys.exc_info()[1]
            return False

        try:
            if not httpService.isResponseStastusCodeOk(http_response):
                print "Cert. Validate recaptcha response. Get invalid response from validation server: ", str(http_response.getStatusLine().getStatusCode())
                httpService.consume(http_response)
                return False
    
            response_bytes = httpService.getResponseContent(http_response)
            response_string = httpService.convertEntityToString(response_bytes)
            httpService.consume(http_response)
        finally:
            http_service_response.closeConnection()

        if response_string == None:
            print "Cert. Validate recaptcha response. Get empty response from validation server"
            return False
        
        response = json.loads(response_string)
        
        return response["success"]
    def prepareForStep(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        authenticationService = AuthenticationService.instance()
        httpService = HttpService.instance()

        cas_host = configurationAttributes.get("cas_host").getValue2()
        cas_renew_opt = StringHelper.toBoolean(
            configurationAttributes.get("cas_renew_opt").getValue2(), False)

        cas_extra_opts = None
        if (configurationAttributes.containsKey("cas_extra_opts")):
            cas_extra_opts = configurationAttributes.get(
                "cas_extra_opts").getValue2()

        if (step == 1):
            print "CAS2. Prepare for step 1"

            request = FacesContext.getCurrentInstance().getExternalContext(
            ).getRequest()
            parametersMap = HashMap()
            parametersMap.put(
                "service",
                httpService.constructServerUrl(request) + "/postlogin")
            if (cas_renew_opt):
                parametersMap.put("renew", "true")
            cas_service_request_uri = authenticationService.parametersAsString(
                parametersMap)
            cas_service_request_uri = cas_host + "/login?" + cas_service_request_uri
            if cas_extra_opts != None:
                cas_service_request_uri = cas_service_request_uri + "&" + cas_extra_opts

            print "CAS2. Prepare for step 1. cas_service_request_uri: " + cas_service_request_uri

            context.set("cas_service_request_uri", cas_service_request_uri)

            return True
        elif (step == 2):
            print "CAS2. Prepare for step 2"

            return True
        else:
            return False
Beispiel #14
0
    def determineGeolocationData(self, remote_ip):
        print "Super-Gluu. Determine remote location. remote_ip: '%s'" % remote_ip
        httpService = HttpService.instance()

        http_client = httpService.getHttpsClient()
        http_client_params = http_client.getParams()
        http_client_params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15 * 1000)
        
        geolocation_service_url = "http://ip-api.com/json/%s?fields=49177" % remote_ip
        geolocation_service_headers = { "Accept" : "application/json" }

        try:
            http_service_response = httpService.executeGet(http_client, geolocation_service_url,  geolocation_service_headers)
            http_response = http_service_response.getHttpResponse()
        except:
            print "Super-Gluu. Determine remote location. Exception: ", sys.exc_info()[1]
            return None

        try:
            if not httpService.isResponseStastusCodeOk(http_response):
                print "Super-Gluu. Determine remote location. Get invalid response from validation server: ", str(http_response.getStatusLine().getStatusCode())
                httpService.consume(http_response)
                return None
    
            response_bytes = httpService.getResponseContent(http_response)
            response_string = httpService.convertEntityToString(response_bytes)
            httpService.consume(http_response)
        finally:
            http_service_response.closeConnection()

        if response_string == None:
            print "Super-Gluu. Determine remote location. Get empty response from location server"
            return None
        
        response = json.loads(response_string)
        
        if not StringHelper.equalsIgnoreCase(response['status'], "success"):
            print "Super-Gluu. Determine remote location. Get response with status: '%s'" % response['status']
            return None

        return response
Beispiel #15
0
    def validateInweboToken(self, iw_api_uri, iw_service_id, user_name,
                            iw_token):
        httpService = HttpService.instance()
        xmlService = XmlService.instance()

        if StringHelper.isEmpty(iw_token):
            print "InWebo. Token verification. iw_token is empty"
            return False

        request_uri = iw_api_uri + "?action=authenticate" + "&serviceId=" + httpService.encodeUrl(
            iw_service_id) + "&userId=" + httpService.encodeUrl(
                user_name) + "&token=" + httpService.encodeUrl(iw_token)
        print "InWebo. Token verification. Attempting to send authentication request:", request_uri
        # Execute request
        http_response = httpService.executeGet(self.client, request_uri)

        # Validate response code
        response_validation = httpService.isResponseStastusCodeOk(
            http_response)
        if response_validation == False:
            print "InWebo. Token verification. Get unsuccessful response code"
            return False

        authentication_response_bytes = httpService.getResponseContent(
            http_response)
        print "InWebo. Token verification. Get response:", httpService.convertEntityToString(
            authentication_response_bytes)

        # Validate authentication response
        response_validation = httpService.isContentTypeXml(http_response)
        if response_validation == False:
            print "InWebo. Token verification. Get invalid response"
            return False

        # Parse XML response
        try:
            xmlDocument = xmlService.getXmlDocument(
                authentication_response_bytes)
        except Exception, err:
            print "InWebo. Token verification. Failed to parse XML response:", err
            return False
    def prepareForStep(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        authenticationService = AuthenticationService.instance()
        httpService = HttpService.instance();

        cas_host = configurationAttributes.get("cas_host").getValue2()
        cas_renew_opt = StringHelper.toBoolean(configurationAttributes.get("cas_renew_opt").getValue2(), False)

        cas_extra_opts = None
        if (configurationAttributes.containsKey("cas_extra_opts")):
            cas_extra_opts = configurationAttributes.get("cas_extra_opts").getValue2()

        if (step == 1):
            print "CAS2. Prepare for step 1"

            print "CAS2. Prepare for step 1. Store current request parameters in session because CAS don't pass them via service URI"
            authenticationService.storeRequestParametersInSession()

            request = FacesContext.getCurrentInstance().getExternalContext().getRequest()
            parametersMap = HashMap()
            parametersMap.put("service", httpService.constructServerUrl(request) + "/postlogin")
            if (cas_renew_opt):
                parametersMap.put("renew", "true")
            cas_service_request_uri = authenticationService.parametersAsString(parametersMap)
            cas_service_request_uri = cas_host + "/login?" + cas_service_request_uri
            if cas_extra_opts != None:
                cas_service_request_uri = cas_service_request_uri + "&" + cas_extra_opts

            print "CAS2. Prepare for step 1. cas_service_request_uri: " + cas_service_request_uri

            context.set("cas_service_request_uri", cas_service_request_uri)

            return True
        elif (step == 2):
            print "CAS2. Prepare for step 2"

            return True
        else:
            return False
    def validateRecaptcha(self, recaptcha_response):
        print "Cert. Validate recaptcha response"

        request = FacesContext.getCurrentInstance().getExternalContext(
        ).getRequest()
        remoteip = request.getHeader("X-FORWARDED-FOR")
        if remoteip == None:
            remoteip = request.getRemoteAddr()
        print "Cert. Validate recaptcha response. remoteip: '%s'" % remoteip

        httpService = HttpService.instance()

        http_client = httpService.getHttpsClient()
        http_client_params = http_client.getParams()
        http_client_params.setIntParameter(
            CoreConnectionPNames.CONNECTION_TIMEOUT, 15 * 1000)

        recaptcha_validation_url = "https://www.google.com/recaptcha/api/siteverify"
        recaptcha_validation_request = urllib.urlencode({
            "secret":
            self.recaptcha_creds['secret_key'],
            "response":
            recaptcha_response,
            "remoteip":
            remoteip
        })
        recaptcha_validation_headers = {
            "Content-type": "application/x-www-form-urlencoded",
            "Accept": "application/json"
        }

        try:
            http_service_response = httpService.executePost(
                http_client, recaptcha_validation_url, None,
                recaptcha_validation_headers, recaptcha_validation_request)
            http_response = http_service_response.getHttpResponse()
        except:
            print "Cert. Validate recaptcha response. Exception: ", sys.exc_info(
            )[1]
            return False

        try:
            if not httpService.isResponseStastusCodeOk(http_response):
                print "Cert. Validate recaptcha response. Get invalid response from validation server: ", str(
                    http_response.getStatusLine().getStatusCode())
                httpService.consume(http_response)
                return False

            response_bytes = httpService.getResponseContent(http_response)
            response_string = httpService.convertEntityToString(response_bytes)
            httpService.consume(http_response)
        finally:
            http_service_response.closeConnection()

        if response_string == None:
            print "Cert. Validate recaptcha response. Get empty response from validation server"
            return False

        response = json.loads(response_string)

        return response["success"]
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        authenticationService = AuthenticationService.instance()
        userService = UserService.instance()
        httpService = HttpService.instance()

        cas_host = configurationAttributes.get("cas_host").getValue2()
        cas_map_user = StringHelper.toBoolean(
            configurationAttributes.get("cas_map_user").getValue2(), False)
        cas_renew_opt = StringHelper.toBoolean(
            configurationAttributes.get("cas_renew_opt").getValue2(), False)

        cas_extra_opts = None
        if (configurationAttributes.containsKey("cas_extra_opts")):
            cas_extra_opts = configurationAttributes.get(
                "cas_extra_opts").getValue2()

        if (step == 1):
            print "CAS2. Authenticate for step 1"
            ticket_array = requestParameters.get("ticket")
            if ArrayHelper.isEmpty(ticket_array):
                print "CAS2. Authenticate for step 1. ticket is empty"
                return False

            ticket = ticket_array[0]
            print "CAS2. Authenticate for step 1. ticket: " + ticket

            if (StringHelper.isEmptyString(ticket)):
                print "CAS2. Authenticate for step 1. ticket is invalid"
                return False

            # Validate ticket
            request = FacesContext.getCurrentInstance().getExternalContext(
            ).getRequest()

            parametersMap = HashMap()
            parametersMap.put(
                "service",
                httpService.constructServerUrl(request) + "/postlogin")
            if (cas_renew_opt):
                parametersMap.put("renew", "true")
            parametersMap.put("ticket", ticket)
            cas_service_request_uri = authenticationService.parametersAsString(
                parametersMap)
            cas_service_request_uri = cas_host + "/serviceValidate?" + cas_service_request_uri
            if (cas_extra_opts != None):
                cas_service_request_uri = cas_service_request_uri + "&" + cas_extra_opts

            print "CAS2. Authenticate for step 1. cas_service_request_uri: " + cas_service_request_uri

            http_client = httpService.getHttpsClient()
            http_service_response = httpService.executeGet(
                http_client, cas_service_request_uri)

            try:
                validation_content = httpService.convertEntityToString(
                    httpService.getResponseContent(
                        http_service_response.getHttpResponse()))
            finally:
                http_service_response.closeConnection()

            print "CAS2. Authenticate for step 1. validation_content: " + validation_content
            if StringHelper.isEmpty(validation_content):
                print "CAS2. Authenticate for step 1. Ticket validation response is invalid"
                return False

            cas2_auth_failure = self.parse_tag(validation_content,
                                               "cas:authenticationFailure")
            print "CAS2. Authenticate for step 1. cas2_auth_failure: ", cas2_auth_failure

            cas2_user_uid = self.parse_tag(validation_content, "cas:user")
            print "CAS2. Authenticate for step 1. cas2_user_uid: ", cas2_user_uid

            if ((cas2_auth_failure != None) or (cas2_user_uid == None)):
                print "CAS2. Authenticate for step 1. Ticket is invalid"
                return False

            if (cas_map_user):
                print "CAS2. Authenticate for step 1. Attempting to find user by oxExternalUid: cas2:" + cas2_user_uid

                # Check if the is user with specified cas2_user_uid
                find_user_by_uid = userService.getUserByAttribute(
                    "oxExternalUid", "cas2:" + cas2_user_uid)

                if (find_user_by_uid == None):
                    print "CAS2. Authenticate for step 1. Failed to find user"
                    print "CAS2. Authenticate for step 1. Setting count steps to 2"
                    context.set("cas2_count_login_steps", 2)
                    context.set("cas2_user_uid", cas2_user_uid)
                    return True

                found_user_name = find_user_by_uid.getUserId()
                print "CAS2. Authenticate for step 1. found_user_name: " + found_user_name

                credentials = Identity.instance().getCredentials()
                credentials.setUsername(found_user_name)
                credentials.setUser(find_user_by_uid)

                print "CAS2. Authenticate for step 1. Setting count steps to 1"
                context.set("cas2_count_login_steps", 1)

                return True
            else:
                print "CAS2. Authenticate for step 1. Attempting to find user by uid:" + cas2_user_uid

                # Check if the is user with specified cas2_user_uid
                find_user_by_uid = userService.getUser(cas2_user_uid)
                if (find_user_by_uid == None):
                    print "CAS2. Authenticate for step 1. Failed to find user"
                    return False

                found_user_name = find_user_by_uid.getUserId()
                print "CAS2. Authenticate for step 1. found_user_name: " + found_user_name

                credentials = Identity.instance().getCredentials()
                credentials.setUsername(found_user_name)
                credentials.setUser(find_user_by_uid)

                print "CAS2. Authenticate for step 1. Setting count steps to 1"
                context.set("cas2_count_login_steps", 1)

                return True
        elif (step == 2):
            print "CAS2. Authenticate for step 2"

            sessionAttributes = context.get("sessionAttributes")
            if (sessionAttributes == None
                ) or not sessionAttributes.containsKey("cas2_user_uid"):
                print "CAS2. Authenticate for step 2. cas2_user_uid is empty"
                return False

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

            credentials = Identity.instance().getCredentials()
            user_name = credentials.getUsername()
            user_password = credentials.getPassword()

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

            if (not logged_in):
                return False

            # Check if there is user which has cas2_user_uid
            # Avoid mapping CAS2 account to more than one IDP account
            find_user_by_uid = userService.getUserByAttribute(
                "oxExternalUid", "cas2:" + cas2_user_uid)

            if (find_user_by_uid == None):
                # Add cas2_user_uid to user one id UIDs
                find_user_by_uid = userService.addUserAttribute(
                    user_name, "oxExternalUid", "cas2:" + cas2_user_uid)
                if (find_user_by_uid == None):
                    print "CAS2. Authenticate for step 2. Failed to update current user"
                    return False

                return True
            else:
                found_user_name = find_user_by_uid.getUserId()
                print "CAS2. Authenticate for step 2. found_user_name: " + found_user_name

                if StringHelper.equals(user_name, found_user_name):
                    return True

            return False
        else:
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        authenticationService = AuthenticationService.instance()
        userService = UserService.instance()
        httpService = HttpService.instance()

        server_flag = configurationAttributes.get(
            "oneid_server_flag").getValue2()
        callback_attrs = configurationAttributes.get(
            "oneid_callback_attrs").getValue2()
        creds_file = configurationAttributes.get(
            "oneid_creds_file").getValue2()

        # Create OneID
        authn = OneID(server_flag)

        # Set path to credentials file
        authn.creds_file = creds_file

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

            # Find OneID request
            json_data_array = requestParameters.get("json_data")
            if ArrayHelper.isEmpty(json_data_array):
                print "OneId. Authenticate for step 1. json_data is empty"
                return False

            request = json_data_array[0]
            print "OneId. Authenticate for step 1. request: " + request

            if (StringHelper.isEmptyString(request)):
                return False

            authn.set_credentials()

            # Validate request
            http_client = httpService.getHttpsClientDefaulTrustStore()
            auth_data = httpService.encodeBase64(authn.api_id + ":" +
                                                 authn.api_key)
            http_response = httpService.executePost(
                http_client, authn.helper_server + "/validate", auth_data,
                request, ContentType.APPLICATION_JSON)
            validation_content = httpService.convertEntityToString(
                httpService.getResponseContent(http_response))
            print "OneId. Authenticate for step 1. validation_content: " + validation_content

            if (StringHelper.isEmptyString(validation_content)):
                return False

            validation_resp = json.loads(validation_content)
            print "OneId. Authenticate for step 1. validation_resp: " + str(
                validation_resp)

            if (not authn.success(validation_resp)):
                return False

            response = json.loads(request)
            for x in validation_resp:
                response[x] = validation_resp[x]

            oneid_user_uid = response['uid']
            print "OneId. Authenticate for step 1. oneid_user_uid: " + oneid_user_uid

            # Check if the is user with specified oneid_user_uid
            find_user_by_uid = userService.getUserByAttribute(
                "oxExternalUid", "oneid:" + oneid_user_uid)

            if (find_user_by_uid == None):
                print "OneId. Authenticate for step 1. Failed to find user"
                print "OneId. Authenticate for step 1. Setting count steps to 2"
                context.set("oneid_count_login_steps", 2)
                context.set("oneid_user_uid", oneid_user_uid)
                return True

            found_user_name = find_user_by_uid.getUserId()
            print "OneId. Authenticate for step 1. found_user_name: " + found_user_name

            credentials = Identity.instance().getCredentials()
            credentials.setUsername(found_user_name)
            credentials.setUser(find_user_by_uid)

            print "OneId. Authenticate for step 1. Setting count steps to 1"
            context.set("oneid_count_login_steps", 1)

            return True
        elif (step == 2):
            print "OneId. Authenticate for step 2"

            sessionAttributes = context.get("sessionAttributes")
            if (sessionAttributes == None
                ) or not sessionAttributes.containsKey("oneid_user_uid"):
                print "OneId. Authenticate for step 2. oneid_user_uid is empty"
                return False

            oneid_user_uid = sessionAttributes.get("oneid_user_uid")
            passed_step1 = StringHelper.isNotEmptyString(oneid_user_uid)
            if (not passed_step1):
                return False
#
            credentials = Identity.instance().getCredentials()

            user_name = credentials.getUsername()
            passed_step1 = StringHelper.isNotEmptyString(user_name)

            if (not passed_step1):
                return False
#
            credentials = Identity.instance().getCredentials()

            user_name = credentials.getUsername()
            user_password = credentials.getPassword()
            logged_in = False
            if (StringHelper.isNotEmptyString(user_name)
                    and StringHelper.isNotEmptyString(user_password)):
                logged_in = userService.authenticate(user_name, user_password)

            if (not logged_in):
                return False

            # Check if there is user which has oneid_user_uid
            # Avoid mapping OneID account to more than one IDP account
            find_user_by_uid = userService.getUserByAttribute(
                "oxExternalUid", "oneid:" + oneid_user_uid)

            if (find_user_by_uid == None):
                # Add oneid_user_uid to user one id UIDs
                find_user_by_uid = userService.addUserAttribute(
                    user_name, "oxExternalUid", "oneid:" + oneid_user_uid)
                if (find_user_by_uid == None):
                    print "OneId. Authenticate for step 2. Failed to update current user"
                    return False

                return True
            else:
                found_user_name = find_user_by_uid.getUserId()
                print "OneId. Authenticate for step 2. found_user_name: " + found_user_name

                if StringHelper.equals(user_name, found_user_name):
                    return True

            return False
        else:
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        authenticationService = AuthenticationService.instance()
        userService = UserService.instance()
        httpService = HttpService.instance();

        server_flag = configurationAttributes.get("oneid_server_flag").getValue2()
        callback_attrs = configurationAttributes.get("oneid_callback_attrs").getValue2()
        creds_file = configurationAttributes.get("oneid_creds_file").getValue2()

        # Create OneID
        authn = OneID(server_flag)

        # Set path to credentials file
        authn.creds_file = creds_file;

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

            # Find OneID request
            json_data_array = requestParameters.get("json_data")
            if ArrayHelper.isEmpty(json_data_array):
                print "OneId. Authenticate for step 1. json_data is empty"
                return False

            request = json_data_array[0]
            print "OneId. Authenticate for step 1. request: " + request

            if (StringHelper.isEmptyString(request)):
                return False
            
            authn.set_credentials()

            # Validate request
            http_client = httpService.getHttpsClientDefaulTrustStore();
            auth_data = httpService.encodeBase64(authn.api_id + ":" + authn.api_key)
            http_response = httpService.executePost(http_client, authn.helper_server + "/validate", auth_data, request, ContentType.APPLICATION_JSON)
            validation_content = httpService.convertEntityToString(httpService.getResponseContent(http_response))
            print "OneId. Authenticate for step 1. validation_content: " + validation_content
            
            if (StringHelper.isEmptyString(validation_content)):
                return False

            validation_resp = json.loads(validation_content)
            print "OneId. Authenticate for step 1. validation_resp: " + str(validation_resp)

            if (not authn.success(validation_resp)):
                return False

            response = json.loads(request)
            for x in validation_resp:
                response[x] = validation_resp[x]

            oneid_user_uid = response['uid']
            print "OneId. Authenticate for step 1. oneid_user_uid: " + oneid_user_uid

            # Check if the is user with specified oneid_user_uid
            find_user_by_uid = userService.getUserByAttribute("oxExternalUid", "oneid:" + oneid_user_uid)

            if (find_user_by_uid == None):
                print "OneId. Authenticate for step 1. Failed to find user"
                print "OneId. Authenticate for step 1. Setting count steps to 2"
                context.set("oneid_count_login_steps", 2)
                context.set("oneid_user_uid", oneid_user_uid)
                return True

            found_user_name = find_user_by_uid.getUserId()
            print "OneId. Authenticate for step 1. found_user_name: " + found_user_name

            credentials = Identity.instance().getCredentials()
            credentials.setUsername(found_user_name)
            credentials.setUser(find_user_by_uid)
            
            print "OneId. Authenticate for step 1. Setting count steps to 1"
            context.set("oneid_count_login_steps", 1)

            return True
        elif (step == 2):
            print "OneId. Authenticate for step 2"

            sessionAttributes = context.get("sessionAttributes")
            if (sessionAttributes == None) or not sessionAttributes.containsKey("oneid_user_uid"):
                print "OneId. Authenticate for step 2. oneid_user_uid is empty"
                return False

            oneid_user_uid = sessionAttributes.get("oneid_user_uid")
            passed_step1 = StringHelper.isNotEmptyString(oneid_user_uid)
            if (not passed_step1):
                return False
#
            credentials = Identity.instance().getCredentials()

            user_name = credentials.getUsername()
            passed_step1 = StringHelper.isNotEmptyString(user_name)

            if (not passed_step1):
                return False
#
            credentials = Identity.instance().getCredentials()

            user_name = credentials.getUsername()
            user_password = credentials.getPassword()
            logged_in = False
            if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)):
                logged_in = userService.authenticate(user_name, user_password)

            if (not logged_in):
                return False

            # Check if there is user which has oneid_user_uid
            # Avoid mapping OneID account to more than one IDP account
            find_user_by_uid = userService.getUserByAttribute("oxExternalUid", "oneid:" + oneid_user_uid)

            if (find_user_by_uid == None):
                # Add oneid_user_uid to user one id UIDs
                find_user_by_uid = userService.addUserAttribute(user_name, "oxExternalUid", "oneid:" + oneid_user_uid)
                if (find_user_by_uid == None):
                    print "OneId. Authenticate for step 2. Failed to update current user"
                    return False

                return True
            else:
                found_user_name = find_user_by_uid.getUserId()
                print "OneId. Authenticate for step 2. found_user_name: " + found_user_name
    
                if StringHelper.equals(user_name, found_user_name):
                    return True
        
            return False
        else:
            return False
    def authenticate(self, configurationAttributes, requestParameters, step):
        context = Contexts.getEventContext()
        authenticationService = AuthenticationService.instance()
        userService = UserService.instance()
        httpService = HttpService.instance();

        stringEncrypter = StringEncrypter.defaultInstance()

        cas_host = configurationAttributes.get("cas_host").getValue2()
        cas_extra_opts = configurationAttributes.get("cas_extra_opts").getValue2()
        cas_map_user = StringHelper.toBoolean(configurationAttributes.get("cas_map_user").getValue2(), False)
        cas_renew_opt = StringHelper.toBoolean(configurationAttributes.get("cas_renew_opt").getValue2(), False)

        if (step == 1):
            print "CAS2 authenticate for step 1"
            ticket_array = requestParameters.get("ticket")
            if ArrayHelper.isEmpty(ticket_array):
                print "CAS2 authenticate for step 1. ticket is empty"
                return False

            ticket = ticket_array[0]
            print "CAS2 authenticate for step 1. ticket: " + ticket

            if (StringHelper.isEmptyString(ticket)):
                print "CAS2 authenticate for step 1. ticket is invalid"
                return False

            # Validate ticket
            request = FacesContext.getCurrentInstance().getExternalContext().getRequest()

            parametersMap = HashMap()
            parametersMap.put("service", httpService.constructServerUrl(request) + "/postlogin")
            if (cas_renew_opt):
                parametersMap.put("renew", "true")
            parametersMap.put("ticket", ticket)
            cas_service_request_uri = authenticationService.parametersAsString(parametersMap)
            cas_service_request_uri = cas_host + "/serviceValidate?" + cas_service_request_uri
            if StringHelper.isNotEmpty(cas_extra_opts):
                cas_service_request_uri = cas_service_request_uri + "&" + cas_extra_opts

            print "CAS2 authenticate for step 1. cas_service_request_uri: " + cas_service_request_uri

            http_client = httpService.getHttpsClientTrustAll();
            http_response = httpService.executeGet(http_client, cas_service_request_uri)
            validation_content = httpService.convertEntityToString(httpService.getResponseContent(http_response))
            print "CAS2 authenticate for step 1. validation_content: " + validation_content
            if StringHelper.isEmpty(validation_content):
                print "CAS2 authenticate for step 1. Ticket validation response is invalid"
                return False

            cas2_auth_failure = self.parse_tag(validation_content, "cas:authenticationFailure")
            print "CAS2 authenticate for step 1. cas2_auth_failure: ", cas2_auth_failure

            cas2_user_uid = self.parse_tag(validation_content, "cas:user")
            print "CAS2 authenticate for step 1. cas2_user_uid: ", cas2_user_uid
            
            if ((cas2_auth_failure != None) or (cas2_user_uid == None)):
                print "CAS2 authenticate for step 1. Ticket is invalid"
                return False

            if (cas_map_user):
                print "CAS2 authenticate for step 1. Attempting to find user by oxExternalUid: cas2:" + cas2_user_uid

                # Check if the is user with specified cas2_user_uid
                find_user_by_uid = userService.getUserByAttribute("oxExternalUid", "cas2:" + cas2_user_uid)

                if (find_user_by_uid == None):
                    print "CAS2 authenticate for step 1. Failed to find user"
                    print "CAS2 authenticate for step 1. Setting count steps to 2"
                    context.set("cas2_count_login_steps", 2)
                    context.set("cas2_user_uid", stringEncrypter.encrypt(cas2_user_uid))
                    return True

                found_user_name = find_user_by_uid.getUserId()
                print "CAS2 authenticate for step 1. found_user_name: " + found_user_name

                credentials = Identity.instance().getCredentials()
                credentials.setUsername(found_user_name)
                credentials.setUser(find_user_by_uid)
            
                print "CAS2 authenticate for step 1. Setting count steps to 1"
                context.set("cas2_count_login_steps", 1)

                return True
            else:
                print "CAS2 authenticate for step 1. Attempting to find user by uid:" + cas2_user_uid

                # Check if the is user with specified cas2_user_uid
                find_user_by_uid = userService.getUser(cas2_user_uid)
                if (find_user_by_uid == None):
                    print "CAS2 authenticate for step 1. Failed to find user"
                    return False

                found_user_name = find_user_by_uid.getUserId()
                print "CAS2 authenticate for step 1. found_user_name: " + found_user_name

                credentials = Identity.instance().getCredentials()
                credentials.setUsername(found_user_name)
                credentials.setUser(find_user_by_uid)

                print "CAS2 authenticate for step 1. Setting count steps to 1"
                context.set("cas2_count_login_steps", 1)

                return True
        elif (step == 2):
            print "CAS2 authenticate for step 2"
            
            cas2_user_uid_array = requestParameters.get("cas2_user_uid")
            if ArrayHelper.isEmpty(cas2_user_uid_array):
                print "CAS2 authenticate for step 2. cas2_user_uid is empty"
                return False

            cas2_user_uid = stringEncrypter.decrypt(cas2_user_uid_array[0])
            passed_step1 = StringHelper.isNotEmptyString(cas2_user_uid)
            if (not passed_step1):
                return False

            credentials = Identity.instance().getCredentials()
            user_name = credentials.getUsername()
            user_password = credentials.getPassword()

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

            if (not logged_in):
                return False

            # Check if there is user which has cas2_user_uid
            # Avoid mapping CAS2 account to more than one IDP account
            find_user_by_uid = userService.getUserByAttribute("oxExternalUid", "cas2:" + cas2_user_uid)

            if (find_user_by_uid == None):
                # Add cas2_user_uid to user one id UIDs
                find_user_by_uid = userService.addUserAttribute(user_name, "oxExternalUid", "cas2:" + cas2_user_uid)
                if (find_user_by_uid == None):
                    print "CAS2 authenticate for step 2. Failed to update current user"
                    return False

                return True
            else:
                found_user_name = find_user_by_uid.getUserId()
                print "CAS2 authenticate for step 2. found_user_name: " + found_user_name
    
                if StringHelper.equals(user_name, found_user_name):
                    return True
        
            return False
        else:
            return False