def authenticate(self, configurationAttributes, requestParameters, step): authenticationService = CdiUtil.bean(AuthenticationService) identity = CdiUtil.bean(Identity) credentials = identity.getCredentials() session_attributes = identity.getSessionId().getSessionAttributes() client_id = session_attributes.get("client_id") print "Basic (client group). Get client_id: '%s' authorization request" % client_id user_groups = self.client_configurations.get(client_id) if user_groups == None: print "Basic (client group). There is no user groups configuration for client_id '%s'. allow_default_login: %s" % (client_id, self.allow_default_login) if not self.allow_default_login: return False result = self.authenticateImpl(credentials, authenticationService) return result is_member_client_groups = self.isUserMemberOfGroups(credentials, user_groups) if not is_member_client_groups: print "Basic (client group). User '%s' hasn't permissions to log into client_id '%s' application. " % (credentials.getUsername(), client_id) return False result = self.authenticateImpl(credentials, authenticationService) return result
def prepareForStep(self, configurationAttributes, requestParameters, step): if step == 1: print "CAS2. Prepare for step 1" requestParameterService = CdiUtil.bean(RequestParameterService) httpService = CdiUtil.bean(HttpService) facesContext = CdiUtil.bean(FacesContext) request = facesContext.getExternalContext().getRequest() parametersMap = HashMap() parametersMap.put("service", httpService.constructServerUrl(request) + "/postlogin.htm") if self.cas_renew_opt: parametersMap.put("renew", "true") cas_service_request_uri = requestParameterService.parametersAsString(parametersMap) cas_service_request_uri = self.cas_host + "/login?" + cas_service_request_uri if self.cas_extra_opts != None: cas_service_request_uri = cas_service_request_uri + "&" + self.cas_extra_opts print "CAS2. Prepare for step 1. cas_service_request_uri: " + cas_service_request_uri facesService = CdiUtil.bean(FacesService) facesService.redirectToExternalURL(cas_service_request_uri) return True elif step == 2: print "CAS2. Prepare for step 2" return True else: return False
def authenticate(self, configurationAttributes, requestParameters, step): print "BioID. Authenticate " authenticationService = CdiUtil.bean(AuthenticationService) identity = CdiUtil.bean(Identity) credentials = identity.getCredentials() user_name = credentials.getUsername() if (step == 1): print "BioID. Authenticate for step 1" logged_in = False userService = CdiUtil.bean(UserService) authenticated_user = self.processBasicAuthentication(credentials) if authenticated_user == None: print "BioID. User does not exist" return False identity.setWorkingParameter("user_name",user_name) bcid = self.STORAGE + "." + self.PARTITION + "." + str(String(user_name).hashCode()) print "BioID. username:bcid %s:%s" %(user_name, bcid) is_user_enrolled = self.isenrolled(bcid) print "BioID. is_user_enrolled: '%s'" % is_user_enrolled if(is_user_enrolled == True): identity.setWorkingParameter("bioID_auth_method","verification") else: identity.setWorkingParameter("bioID_auth_method","enrollment") identity.setWorkingParameter("bioID_count_login_steps", 2) return True elif step == 2 or step == 3: auth_method = identity.getWorkingParameter("bioID_auth_method") print "BioID. Authenticate method for step %s. bioID_auth_method: '%s'" % (step,auth_method) user_name = identity.getWorkingParameter("user_name") bcid = self.STORAGE + "." + self.PARTITION + "." + str(String(user_name).hashCode()) if step == 2 and 'enrollment' == auth_method: access_token = identity.getWorkingParameter("access_token") result = self.performBiometricOperation( access_token, "enroll") if result == True: #this means that enroll is a success, the next is step 3 authenticate identity.setWorkingParameter("bioID_count_login_steps", 3) identity.setWorkingParameter("bioID_auth_method","verification") return result else: return False else : access_token = identity.getWorkingParameter("access_token") result = self.performBiometricOperation( access_token, "verify") return result else: return False
def createLdapExtendedEntryManagers(self, authConfiguration): ldapExtendedConfigurations = self.createLdapExtendedConfigurations(authConfiguration) appInitializer = CdiUtil.bean(AppInitializer) persistanceFactoryService = CdiUtil.bean(PersistanceFactoryService) ldapEntryManagerFactory = persistanceFactoryService.getPersistenceEntryManagerFactory(LdapEntryManagerFactory) persistenceType = ldapEntryManagerFactory.getPersistenceType() ldapExtendedEntryManagers = [] for ldapExtendedConfiguration in ldapExtendedConfigurations: connectionConfiguration = ldapExtendedConfiguration["connectionConfiguration"] ldapProperties = Properties() for key, value in connectionConfiguration.items(): value_string = value if isinstance(value_string, list): value_string = ", ".join(value) else: value_string = str(value) ldapProperties.setProperty(persistenceType + "." + key, value_string) ldapEntryManager = ldapEntryManagerFactory.createEntryManager(ldapProperties) ldapExtendedEntryManagers.append({ "ldapConfiguration" : ldapExtendedConfiguration["ldapConfiguration"], "ldapProperties" : ldapProperties, "loginAttributes" : ldapExtendedConfiguration["loginAttributes"], "localLoginAttributes" : ldapExtendedConfiguration["localLoginAttributes"], "ldapEntryManager" : ldapEntryManager }) return ldapExtendedEntryManagers
def prepareForStep(self, configurationAttributes, requestParameters, step): identity = CdiUtil.bean(Identity) authenticationService = CdiUtil.bean(AuthenticationService) duo_host = configurationAttributes.get("duo_host").getValue2() if (step == 1): print "Duo. Prepare for step 1" return True elif (step == 2): print "Duo. Prepare for step 2" user = authenticationService.getAuthenticatedUser() if (user == None): print "Duo. Prepare for step 2. Failed to determine user name" return False user_name = user.getUserId() duo_sig_request = duo_web.sign_request(self.ikey, self.skey, self.akey, user_name) print "Duo. Prepare for step 2. duo_sig_request: " + duo_sig_request identity.setWorkingParameter("duo_host", duo_host) identity.setWorkingParameter("duo_sig_request", duo_sig_request) return True else: return False
def modifyIdToken(self, jsonWebResponse, context): print "Update token obconnect script. Modify idToken: %s" % jsonWebResponse try : sessionIdService = CdiUtil.bean(SessionIdService) print "session id from context - %s" % context.getGrant().getSessionDn().strip("oxId=") sessionId = sessionIdService.getSessionByDn(context.getGrant().getSessionDn()) # fetch from persistence print "session id -%s " % sessionId.getSessionAttributes() openbanking_intent_id = sessionId.getSessionAttributes().get("openbanking_intent_id") acr = sessionId.getSessionAttributes().get("acr_ob") # An example of how to set header claims #jsonWebResponse.getHeader().setClaim("custom_header_name", "custom_header_value") #custom claims jsonWebResponse.getClaims().setClaim("openbanking_intent_id", openbanking_intent_id) # If the ASPSP issues a refresh token, the ASPSP must indicate the date-time at which the refresh token # # will expire in a claim named http://openbanking.org.uk/refresh_token_expires_at in the Id token (returned # by the token end-point or userinfo end-point). Its value MUST be a number containing a NumericDate value, # as specified in https://tools.ietf.org/html/rfc7519#section-2 refresh_token_expires_at = CdiUtil.bean(ConfigurationFactory).getAppConfiguration().getRefreshTokenLifetime() jsonWebResponse.getClaims().setClaim("refresh_token_expires_at", refresh_token_expires_at) # this claim is currently commented and should have the unique id of the user for whom consent was passed # please fill it as per the implementation jsonWebResponse.getClaims().setClaim("sub", openbanking_intent_id) print "Update token script. After modify idToken: %s" % jsonWebResponse # Use this blog to implement how RT claims can be retained. https://github.com/GluuFederation/oxAuth/wiki/Retain-access-token-claim return True except: print "update token failure" , sys.exc_info()[1] 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: encryptionService = CdiUtil.bean(EncryptionService) iw_cert_password = encryptionService.decrypt(iw_cert_password) except: return False httpService = CdiUtil.bean(HttpService) 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 = CdiUtil.bean(HttpService) xmlService = CdiUtil.bean(XmlService) 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, configuration_attributes, request_parameters, step): print "ThumbSignIn. Inside prepareForStep. Step %d" % step identity = CdiUtil.bean(Identity) authentication_service = CdiUtil.bean(AuthenticationService) identity.setWorkingParameter("ts_host", ts_host) identity.setWorkingParameter("ts_statusPath", ts_statusPath) self.set_relying_party_login_url(identity) if step == 1 or step == 3: print "ThumbSignIn. Prepare for step 1" self.initialize_thumbsignin(identity, AUTHENTICATE) return True elif step == 2: print "ThumbSignIn. Prepare for step 2" if identity.isSetWorkingParameter(USER_LOGIN_FLOW): user_login_flow = identity.getWorkingParameter(USER_LOGIN_FLOW) print "ThumbSignIn. Value of user_login_flow is %s" % user_login_flow user = authentication_service.getAuthenticatedUser() if user is None: print "ThumbSignIn. Prepare for step 2. Failed to determine user name" return False user_name = user.getUserId() print "ThumbSignIn. Prepare for step 2. user_name: " + user_name if user_name is None: return False identity.setWorkingParameter(USER_ID, user_name) self.initialize_thumbsignin(identity, REGISTER + "/" + user_name) return True else: return False
def getAlternativeAuthenticationMethod(self, usageType, configurationAttributes): print "Identifier First. getAlternativeAuthenticationMethod" identity = CdiUtil.bean(Identity) user_name = identity.getCredentials().getUsername() print "Identifier First. Inspecting user %s" % user_name attributes=identity.getSessionId().getSessionAttributes() attributes.put("roUserName", user_name) acr = None try: userService = CdiUtil.bean(UserService) foundUser = userService.getUserByAttribute("uid", user_name) if foundUser == None: print "Identifier First. User does not exist" return "" attr = configurationAttributes.get("acr_attribute").getValue2() acr=foundUser.getAttribute(attr) #acr="u2f" or "otp" or "twilio_sms", etc... if acr == None: acr = "basic" except: print "Identifier First. Error looking up user or his preferred method" print "Identifier First. new acr value %s" % acr return acr
def authenticate(self, configurationAttributes, requestParameters, step): authenticationService = CdiUtil.bean(AuthenticationService) if (step == 1): print "Basic. Authenticate for step 1" identity = CdiUtil.bean(Identity) credentials = identity.getCredentials() user_name_array = StringHelper.split(credentials.getUsername(),"+") user_name = None if len(user_name_array) == 2: email_id_array = StringHelper.split(user_name_array[1],"@") user_name = user_name_array[0] + "@"+ email_id_array[1] else: user_name = user_name_array[0] print "Username for authentication is: %s " % user_name user_password = credentials.getPassword() logged_in = False if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)): logged_in = authenticationService.authenticate(user_name, user_password,"mail","mail") if (not logged_in): return False return True else: return False
def prepareForStep(self, configurationAttributes, requestParameters, step): print "Person Authentication. prepare for step... %s" % step jwkSet = JWKSet.load( URL(self.tpp_jwks_url)); signedRequest = ServerUtil.getFirstValue(requestParameters, "request") for key in jwkSet.getKeys() : result = self.isSignatureValid(signedRequest, key) if (result == True): signedJWT = SignedJWT.parse(signedRequest) claims = JSONObject(signedJWT.getJWTClaimsSet().getClaims().get("claims")) print "Person Authentication. claims : %s " % claims.toString() id_token = claims.get("id_token"); openbanking_intent_id = id_token.getJSONObject("openbanking_intent_id").getString("value") print "Person Authentication. openbanking_intent_id %s " % openbanking_intent_id redirectURL = self.redirect_url+"&state="+UUID.randomUUID().toString()+"&intent_id="+openbanking_intent_id identity = CdiUtil.bean(Identity) identity.setWorkingParameter("openbanking_intent_id",openbanking_intent_id) print "OpenBanking. Redirecting to ... %s " % redirectURL facesService = CdiUtil.bean(FacesService) facesService.redirectToExternalURL(redirectURL) return True print "Person Authentication. Call to Jans-auth server's /authorize endpoint should contain openbanking_intent_id as an encoded JWT" return False
def init(self, customScript, configurationAttributes): print "Basic (one session). Initialization" self.entryManager = CdiUtil.bean(PersistenceEntryManager) self.staticConfiguration = CdiUtil.bean(StaticConfiguration) print "Basic (one session). Initialized successfully" return True
def authenticate(self, configurationAttributes, requestParameters, step): authenticationService = CdiUtil.bean(AuthenticationService) if step == 1: print "Basic (one session). Authenticate for step 1" identity = CdiUtil.bean(Identity) credentials = identity.getCredentials() user_name = credentials.getUsername() user_password = credentials.getPassword() logged_in = False if StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password): logged_in = authenticationService.authenticate(user_name, user_password) if not logged_in: return False logged_in = self.isFirstSession(user_name) if not logged_in: facesMessages = CdiUtil.bean(FacesMessages) facesMessages.add(FacesMessage.SEVERITY_ERROR, "Please, end active session first!") return False return True else: return False
def lockUser(self, user_name): if StringHelper.isEmpty(user_name): return None userService = CdiUtil.bean(UserService) cacheService= CdiUtil.bean(CacheService) facesMessages = CdiUtil.bean(FacesMessages) facesMessages.setKeepMessages() find_user_by_uid = userService.getUser(user_name) if (find_user_by_uid == None): return None status_attribute_value = userService.getCustomAttribute(find_user_by_uid, "gluuStatus") if status_attribute_value != None: user_status = status_attribute_value.getValue() if StringHelper.equals(user_status, "inactive"): print "Basic (lock account). Lock user. User '%s' locked already" % user_name return userService.setCustomAttribute(find_user_by_uid, "gluuStatus", "inactive") updated_user = userService.updateUser(find_user_by_uid) object_to_store = json.dumps({'locked': True, 'created': LocalDateTime.now().toString()}, separators=(',',':')) cacheService.put(StringHelper.toString(self.lockExpirationTime), "lock_user_"+user_name, object_to_store); facesMessages.add(FacesMessage.SEVERITY_ERROR, "Your account is locked. Please try again after " + StringHelper.toString(self.lockExpirationTime) + " secs") print "Basic (lock account). Lock user. User '%s' locked" % user_name
def authenticate(self, configurationAttributes, requestParameters, step): authenticationService = CdiUtil.bean(AuthenticationService) if (step == 1): print "Radius. Authenticate for step 1" identity = CdiUtil.bean(Identity) credentials = identity.getCredentials() user_name = credentials.getUsername() user_password = credentials.getPassword() if StringHelper.isNotEmptyString(user_name ) and StringHelper.isNotEmptyString(user_password ): user_exists_in_gluu = authenticationService.authenticate(user_name ) if user_exists_in_gluu : client = RadiusClient(self.RADIUS_SERVER_IP,int (self.RADIUS_SERVER_AUTH_PORT), int(self.RADIUS_SERVER_ACCT_PORT), self.RADIUS_SERVER_SECRET) accessRequest = RadiusPacket(RadiusPacket.ACCESS_REQUEST) userNameAttribute = RadiusAttribute(RadiusAttributeValues.USER_NAME,user_name ) userPasswordAttribute = RadiusAttribute(RadiusAttributeValues.USER_PASSWORD,user_password ) accessRequest.setAttribute(userNameAttribute) accessRequest.setAttribute(userPasswordAttribute) accessResponse = client.authenticate(accessRequest) print "Packet type - %s " % accessResponse.getPacketType() if accessResponse.getPacketType() == RadiusPacket.ACCESS_ACCEPT: return True #elif accessResponse.getPacketType() == RadiusPacket.ACCESS_CHALLENGE: # return False return False
def prepareForStep(self, configurationAttributes, requestParameters, step): print "Cert. Prepare for step %d" % step identity = CdiUtil.bean(Identity) if step == 1: if self.enabled_recaptcha: identity.setWorkingParameter("recaptcha_site_key", self.recaptcha_creds['site_key']) elif step == 2: # Store certificate in session facesContext = CdiUtil.bean(FacesContext) externalContext = facesContext.getExternalContext() request = externalContext.getRequest() # Try to get certificate from header X-ClientCert clientCertificate = externalContext.getRequestHeaderMap().get("X-ClientCert") if clientCertificate != None: x509Certificate = self.certFromPemString(clientCertificate) identity.setWorkingParameter("cert_x509", self.certToString(x509Certificate)) print "Cert. Prepare for step 2. Storing user certificate obtained from 'X-ClientCert' header" return True # Try to get certificate from attribute javax.servlet.request.X509Certificate x509Certificates = request.getAttribute('javax.servlet.request.X509Certificate') if (x509Certificates != None) and (len(x509Certificates) > 0): identity.setWorkingParameter("cert_x509", self.certToString(x509Certificates[0])) print "Cert. Prepare for step 2. Storing user certificate obtained from 'javax.servlet.request.X509Certificate' attribute" return True if step < 4: return True else: return False
def authenticate(self, configurationAttributes, requestParameters, step): authenticationService = CdiUtil.bean(AuthenticationService) if (step == 1): print "Basic (multi login). Authenticate for step 1" identity = CdiUtil.bean(Identity) credentials = identity.getCredentials() key_value = credentials.getUsername() user_password = credentials.getPassword() logged_in = False if (StringHelper.isNotEmptyString(key_value) and StringHelper.isNotEmptyString(user_password)): i = 0 count = len(self.login_attributes_list_array) while (i < count): primary_key = self.login_attributes_list_array[i] local_primary_key = self.local_login_attributes_list_array[i] logged_in = authenticationService.authenticate(key_value, user_password, primary_key, local_primary_key) if (logged_in): return True i += 1 return False else: return False
def prepareForStep(self, configurationAttributes, requestParameters, step): authenticationService = CdiUtil.bean(AuthenticationService) if (step == 1): print "Asimba. Prepare for step 1" httpService = CdiUtil.bean(HttpService) facesContext = CdiUtil.bean(FacesContext) request = facesContext.getExternalContext().getRequest() assertionConsumerServiceUrl = httpService.constructServerUrl(request) + "/postlogin.htm" print "Asimba. Prepare for step 1. Prepared assertionConsumerServiceUrl: '%s'" % assertionConsumerServiceUrl currentSamlConfiguration = self.getCurrentSamlConfiguration(self.samlConfiguration, configurationAttributes, requestParameters) if currentSamlConfiguration == None: print "Asimba. 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 "Asimba. Prepare for step 1. external_auth_request_uri: '%s'" % external_auth_request_uri facesService = CdiUtil.bean(FacesService) facesService.redirectToExternalURL(external_auth_request_uri) return True elif (step == 2): print "Asimba. Prepare for step 2" return True else: return False
def getPassportRedirectUrl(self, provider): # provider is assumed to exist in self.registeredProviders url = None try: facesContext = CdiUtil.bean(FacesContext) tokenEndpoint = "https://%s/passport/token" % facesContext.getExternalContext().getRequest().getServerName() httpService = CdiUtil.bean(HttpService) httpclient = httpService.getHttpsClient() print "Passport. getPassportRedirectUrl. Obtaining token from passport at %s" % tokenEndpoint resultResponse = httpService.executeGet(httpclient, tokenEndpoint, Collections.singletonMap("Accept", "text/json")) httpResponse = resultResponse.getHttpResponse() bytes = httpService.getResponseContent(httpResponse) response = httpService.convertEntityToString(bytes) print "Passport. getPassportRedirectUrl. Response was %s" % httpResponse.getStatusLine().getStatusCode() tokenObj = json.loads(response) url = "/passport/auth/%s/%s" % (provider, tokenObj["token_"]) except: print "Passport. getPassportRedirectUrl. Error building redirect URL: ", sys.exc_info()[1] return url
def prepareForStep(self, configurationAttributes, requestParameters, step): print "Casa. prepareForStep %s" % str(step) identity = CdiUtil.bean(Identity) if step == 1: self.prepareUIParams(identity) return True else: session_attributes = identity.getSessionId().getSessionAttributes() authenticationService = CdiUtil.bean(AuthenticationService) user = authenticationService.getAuthenticatedUser() if user == None: print "Casa. prepareForStep. Cannot retrieve logged user" return False acr = session_attributes.get("ACR") print "Casa. prepareForStep. ACR = %s" % acr identity.setWorkingParameter("methods", ArrayList(self.getAvailMethodsUser(user, acr))) if acr in self.authenticators: module = self.authenticators[acr] return module.prepareForStep(module.configAttrs, requestParameters, step) else: return False
def authenticate(self, configurationAttributes, requestParameters, step): authenticationService = CdiUtil.bean(AuthenticationService) if 1 <= step <= 3: print "Basic (demo reset step). Authenticate for step '%s'" % step identity = CdiUtil.bean(Identity) identity.setWorkingParameter("pass_authentication", False) credentials = identity.getCredentials() user_name = credentials.getUsername() user_password = credentials.getPassword() logged_in = False if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)): userService = CdiUtil.bean(UserService) logged_in = authenticationService.authenticate(user_name, user_password) if (not logged_in): return False identity.setWorkingParameter("pass_authentication", True) return True else: return False
def prepareForStep(self, configurationAttributes, requestParameters, step): identity = CdiUtil.bean(Identity) credentials = identity.getCredentials() self.setRequestScopedParameters(identity) if step == 1: print "OTP. Prepare for step 1" return True elif step == 2: print "OTP. Prepare for step 2" session_id_validation = self.validateSessionId(identity) if not session_id_validation: return False otp_auth_method = identity.getWorkingParameter("otp_auth_method") print "OTP. Prepare for step 2. otp_auth_method: '%s'" % otp_auth_method if otp_auth_method == 'enroll': authenticationService = CdiUtil.bean(AuthenticationService) user = authenticationService.getAuthenticatedUser() if user == None: print "OTP. Prepare for step 2. Failed to load user enty" return False if self.otpType == "hotp": otp_secret_key = self.generateSecretHotpKey() otp_enrollment_request = self.generateHotpSecretKeyUri(otp_secret_key, self.otpIssuer, user.getAttribute("displayName")) elif self.otpType == "totp": otp_secret_key = self.generateSecretTotpKey() otp_enrollment_request = self.generateTotpSecretKeyUri(otp_secret_key, self.otpIssuer, user.getAttribute("displayName")) else: print "OTP. Prepare for step 2. Unknown OTP type: '%s'" % self.otpType return False print "OTP. Prepare for step 2. Prepared enrollment request for user: '******'" % user.getUserId() identity.setWorkingParameter("otp_secret_key", self.toBase64Url(otp_secret_key)) identity.setWorkingParameter("otp_enrollment_request", otp_enrollment_request) return True elif step == 3: print "OTP. Prepare for step 3" session_id_validation = self.validateSessionId(identity) if not session_id_validation: return False otp_auth_method = identity.getWorkingParameter("otp_auth_method") print "OTP. Prepare for step 3. otp_auth_method: '%s'" % otp_auth_method if otp_auth_method == 'enroll': return True return False
def getNextStep(self, configurationAttributes, requestParameters, step): print "Casa. getNextStep called %s" % str(step) if step > 1: acr = ServerUtil.getFirstValue(requestParameters, "alternativeMethod") if acr != None: print "Casa. getNextStep. Use alternative method %s" % acr CdiUtil.bean(Identity).setWorkingParameter("ACR", acr) #retry step with different acr return 2 return -1
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" return True # Parse jwt userInfoJwt = Jwt.parse(ujwt) configObj = CdiUtil.bean(ConfigurationFactory) jwksObj = configObj.getWebKeysConfiguration() jwks = JSONObject(jwksObj) # Validate JWT authCryptoProvider = AuthCryptoProvider() validJwt = authCryptoProvider.verifySignature(userInfoJwt.getSigningInput(), userInfoJwt.getEncodedSignature(), userInfoJwt.getHeader().getKeyId(), jwks, None, userInfoJwt.getHeader().getSignatureAlgorithm()) if validJwt == True: print "user-info jwt is valid" # Get claims from parsed JWT jwtClaims = userInfoJwt.getClaims() jansAdminUIRole = jwtClaims.getClaim("jansAdminUIRole") print "Role obtained from UJWT: " + jansAdminUIRole.getString(0) # fetch role-scope mapping from database scopes = None try: entryManager = CdiUtil.bean(PersistenceEntryManager) adminConf = AdminConf() adminUIConfig = entryManager.find(adminConf.getClass(), "ou=admin-ui,ou=configuration,o=jans") roleScopeMapping = adminUIConfig.getDynamic().getRolePermissionMapping() # roleScopeMapping = adminUIConfig.getDynamic() print roleScopeMapping for ele in roleScopeMapping: if ele.getRole() == jansAdminUIRole.getString(0): scopes = ele.getPermissions() except Exception as e: print "Error: Failed to fetch/parse Admin UI roleScopeMapping from DB" print e print "Following scopes will be added in api token: {}".format(scopes) responseAsJsonObject.accumulate("scope", scopes) except Exception as e: print "Exception occured. Unable to resolve role/scope mapping." print e return True
def authenticate(self, configuration_attributes, request_parameters, step): print "ThumbSignIn. Inside authenticate. Step %d" % step authentication_service = CdiUtil.bean(AuthenticationService) identity = CdiUtil.bean(Identity) identity.setWorkingParameter("ts_host", ts_host) identity.setWorkingParameter("ts_statusPath", ts_statusPath) if step == 1 or step == 3: print "ThumbSignIn. Authenticate for Step %d" % step login_flow = ServerUtil.getFirstValue(request_parameters, "login_flow") print "ThumbSignIn. Value of login_flow parameter is %s" % login_flow # Logic for ThumbSignIn Authentication Flow (Either step 1 or step 3) if login_flow == THUMBSIGNIN_AUTHENTICATION or login_flow == THUMBSIGNIN_LOGIN_POST_REGISTRATION: identity.setWorkingParameter(USER_LOGIN_FLOW, login_flow) print "ThumbSignIn. Value of userLoginFlow is %s" % identity.getWorkingParameter(USER_LOGIN_FLOW) logged_in_status = authentication_service.authenticate(self.get_user_id_from_thumbsignin(request_parameters)) print "ThumbSignIn. logged_in status : %r" % logged_in_status return logged_in_status # Logic for traditional login flow (step 1) print "ThumbSignIn. User credentials login flow" identity.setWorkingParameter(USER_LOGIN_FLOW, THUMBSIGNIN_REGISTRATION) print "ThumbSignIn. Value of userLoginFlow is %s" % identity.getWorkingParameter(USER_LOGIN_FLOW) logged_in = self.authenticate_user_credentials(identity, authentication_service) print "ThumbSignIn. Status of User Credentials based Authentication : %r" % logged_in # When the traditional login fails, reinitialize the ThumbSignIn data before sending error response to UI if not logged_in: self.initialize_thumbsignin(identity, AUTHENTICATE) return False print "ThumbSignIn. Authenticate successful for step %d" % step return True elif step == 2: print "ThumbSignIn. Registration flow (step 2)" self.verify_user_login_flow(identity) user = self.get_authenticated_user_from.jans.authentication_service) if user is None: print "ThumbSignIn. Registration flow (step 2). Failed to determine user name" return False user_name = user.getUserId() print "ThumbSignIn. Registration flow (step 2) successful. user_name: %s" % user_name return True else: return False
def authenticate(self, configurationAttributes, requestParameters, step): print("WWPass. Authenticate for step %d" %step) authenticationService = CdiUtil.bean(AuthenticationService) userService = CdiUtil.bean(UserService) ticket = requestParameters.get('wwp_ticket')[0] if 'wwp_ticket' in requestParameters else None identity = CdiUtil.bean(Identity) identity.setWorkingParameter("errors", "") result = self.doAuthenticate(step, requestParameters, userService, authenticationService, identity, ticket) if result and self.sso_cookie_tags: externalContext = CdiUtil.bean(FacesContext).getExternalContext() for tag in self.sso_cookie_tags: externalContext.addResponseCookie("sso_magic_%s"%tag, "auth", {"path":"/", "domain":self.sso_cookie_domain, "maxAge": CdiUtil.bean(AppConfiguration).getSessionIdUnusedLifetime()}) return result
def getPageForStep(self, configurationAttributes, step): print "TwilioSMS. getPageForStep called %s" % step print "numbers are %s" % CdiUtil.bean(Identity).getWorkingParameter("numbers") defPage = "/casa/otp_sms.xhtml" if step == 2: if CdiUtil.bean(Identity).getWorkingParameter("numbers") == None: return defPage else: return "/casa/otp_sms_prompt.xhtml" elif step == 3: return defPage return ""
def prepareForStep(self, configurationAttributes, requestParameters, step): identity = CdiUtil.bean(Identity) if (step == 1): return True elif (step == 2): print "Fido2. Prepare for step 2" session_id = CdiUtil.bean(SessionIdService).getSessionId() if session_id == None: print "Fido2. Prepare for step 2. Failed to determine session_id" return False authenticationService = CdiUtil.bean(AuthenticationService) user = authenticationService.getAuthenticatedUser() if (user == None): print "Fido2. Prepare for step 2. Failed to determine user name" return False userName = user.getUserId() metaDataConfiguration = self.getMetaDataConfiguration() assertionResponse = None attestationResponse = None # Check if user have registered devices count = CdiUtil.bean(UserService).countFido2RegisteredDevices(userName) if (count > 0): print "Fido2. Prepare for step 2. Call Fido2 endpoint in order to start assertion flow" try: assertionService = Fido2ClientFactory.instance().createAssertionService(metaDataConfiguration) assertionRequest = json.dumps({'username': userName}, separators=(',', ':')) assertionResponse = assertionService.authenticate(assertionRequest).readEntity(java.lang.String) if "internal" in assertionResponse: identity.setWorkingParameter("platformAuthenticatorAvailable", "true") else: identity.setWorkingParameter("platformAuthenticatorAvailable", "false") except ClientErrorException, ex: print "Fido2. Prepare for step 2. Failed to start assertion flow. Exception:", sys.exc_info()[1] return False else: print "Fido2. Prepare for step 2. Call Fido2 endpoint in order to start attestation flow" try: attestationService = Fido2ClientFactory.instance().createAttestationService(metaDataConfiguration) attestationRequest = json.dumps({'username': userName, 'displayName': userName}, separators=(',', ':')) attestationResponse = attestationService.register(attestationRequest).readEntity(java.lang.String) except ClientErrorException, ex: print "Fido2. Prepare for step 2. Failed to start attestation flow. Exception:", sys.exc_info()[1] return False
def authenticate(self, configurationAttributes, requestParameters, step): userService = CdiUtil.bean(UserService) authenticationService = CdiUtil.bean(AuthenticationService) identity = CdiUtil.bean(Identity) credentials = identity.getCredentials() user_name = credentials.getUsername() if (step == 1): print "Basic (with password update). Authenticate for step 1" user_password = credentials.getPassword() logged_in = False if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)): logged_in = authenticationService.authenticate(user_name, user_password) if (not logged_in): return False return True elif (step == 2): print "Basic (with password update). Authenticate for step 2" user = authenticationService.getAuthenticatedUser() if user == None: print "Basic (with password update). Authenticate for step 2. Failed to determine user name" return False user_name = user.getUserId() find_user_by_uid = userService.getUser(user_name) update_button = requestParameters.get("loginForm:updateButton") if ArrayHelper.isEmpty(update_button): return True new_password_array = requestParameters.get("new_password") if ArrayHelper.isEmpty(new_password_array) or StringHelper.isEmpty(new_password_array[0]): print "Basic (with password update). Authenticate for step 2. New password is empty" return False new_password = new_password_array[0] find_user_by_uid.setAttribute("userPassword", new_password) print "Basic (with password update). Authenticate for step 2. Attempting to set new user '%s' password" % user_name userService.updateUser(find_user_by_uid) print "Basic (with password update). Authenticate for step 2. Password updated successfully" return True else: return False