def setRelyingPartyLoginUrl(self, identity): print "ThumbSignIn. Inside setRelyingPartyLoginUrl..." sessionId = identity.getSessionId() sessionAttribute = sessionId.getSessionAttributes() stateJWTToken = sessionAttribute.get("state") relyingPartyLoginUrl = "" relyingPartyId = "" if (stateJWTToken != None): stateJWTTokenArray = String(stateJWTToken).split("\\.") stateJWTTokenPayload = stateJWTTokenArray[1] statePayloadStr = String( Base64Util.base64urldecode(stateJWTTokenPayload), "UTF-8") statePayloadJson = JSONObject(statePayloadStr) print "ThumbSignIn. Value of state JWT token Payload is %s" % statePayloadJson additional_claims = statePayloadJson.get("additional_claims") relyingPartyId = additional_claims.get("relyingPartyId") print "ThumbSignIn. Value of relyingPartyId is %s" % relyingPartyId identity.setWorkingParameter("relyingPartyId", relyingPartyId) if (String(relyingPartyId).startsWith("google.com")): #google.com/a/unphishableenterprise.com relyingPartyIdArray = String(relyingPartyId).split("/") googleDomain = relyingPartyIdArray[2] print "ThumbSignIn. Value of googleDomain is %s" % googleDomain relyingPartyLoginUrl = "https://www.google.com/accounts/AccountChooser?hd=" + googleDomain + "%26continue=https://apps.google.com/user/hub" #elif (String(relyingPartyId).startsWith("xyz")): #relyingPartyLoginUrl = "xyz.com" else: relyingPartyLoginUrl = relyingPartyId print "ThumbSignIn. Value of relyingPartyLoginUrl is %s" % relyingPartyLoginUrl identity.setWorkingParameter("relyingPartyLoginUrl", relyingPartyLoginUrl) return None
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 loadServices(self): if self.DCHOSTS is None: return for host in self.DCHOSTS: url = 'http://%s:9022/sv/*/status' % host fd = None try: try: fd = urllib.urlopen(url) data = '' for d in fd.readlines(): data = data + str(d.strip()) self.SVCBYHOST[host] = [] jo = JSONObject(data) for key in jo.keys(): so = jo.get(key) service = so.get('service') self.SVCBYHOST[host].append(service) if not self.HOSTBYSVC.has_key(service): self.HOSTBYSVC[service] = [] self.HOSTBYSVC[service].append(host) except: # ignore hosts that do not respond pass finally: if fd is not None: fd.close()
def set_relying_party_login_url(identity): print "ThumbSignIn. Inside set_relying_party_login_url..." session_id = identity.getSessionId() session_attribute = session_id.getSessionAttributes() state_jwt_token = session_attribute.get("state") relying_party_login_url = "" if state_jwt_token is not None: state_jwt_token_array = String(state_jwt_token).split("\\.") state_jwt_token_payload = state_jwt_token_array[1] state_payload_str = String(Base64Util.base64urldecode(state_jwt_token_payload), "UTF-8") state_payload_json = JSONObject(state_payload_str) print "ThumbSignIn. Value of state JWT token Payload is %s" % state_payload_json additional_claims = state_payload_json.get("additional_claims") relying_party_id = additional_claims.get(RELYING_PARTY_ID) print "ThumbSignIn. Value of relying_party_id is %s" % relying_party_id identity.setWorkingParameter(RELYING_PARTY_ID, relying_party_id) if String(relying_party_id).startsWith("google.com"): # google.com/a/unphishableenterprise.com relying_party_id_array = String(relying_party_id).split("/") google_domain = relying_party_id_array[2] print "ThumbSignIn. Value of google_domain is %s" % google_domain relying_party_login_url = "https://www.google.com/accounts/AccountChooser?hd="+ google_domain + "%26continue=https://apps.google.com/user/hub" # elif (String(relying_party_id).startsWith("xyz")): # relying_party_login_url = "xyz.com" else: # If relying_party_login_url is empty, Gluu's default login URL will be used relying_party_login_url = "" print "ThumbSignIn. Value of relying_party_login_url is %s" % relying_party_login_url identity.setWorkingParameter(RELYING_PARTY_LOGIN_URL, relying_party_login_url) return None
def authenticate_user_in_azure_ad(self, identity, authentication_service): credentials = identity.getCredentials() user_name = credentials.getUsername() user_password = credentials.getPassword() print "ThumbSignIn. user_name: %s" % user_name logged_in = False if StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password): # Special condition to allow for Gluu admin login if StringHelper.equals(user_name, ADMIN): return self.authenticate_user_in_gluu_ldap(authentication_service, user_name, user_password) # Authenticate user credentials with Azure AD non-interactively azure_auth_response = self.azureAuthConnector.authenticateUserInAzure(azure_tenant_id, user_name, user_password, azure_client_id, azure_client_secret) print "ThumbSignIn. Value of azure_auth_response is %s" % azure_auth_response azure_auth_response_json = JSONObject(azure_auth_response) if azure_auth_response_json.has(azure_user_uuid): # Azure authentication has succeeded. User needs to be enrolled in Gluu LDAP user = self.enroll_azure_user_in_gluu_ldap(azure_auth_response_json) if user is None: # User Enrollment in Gluu LDAP has failed logged_in = False else: # Authenticating the user within Gluu user_authenticated_in_gluu = authentication_service.authenticate(user.getUserId()) print "ThumbSignIn: Authentication status of the user enrolled in Gluu LDAP %r " % user_authenticated_in_gluu return user_authenticated_in_gluu else: # Azure authentication has failed. logged_in = False return logged_in
def performBiometricOperation(self, token, task): httpService = CdiUtil.bean(HttpService) http_client = httpService.getHttpsClient() http_client_params = http_client.getParams() bioID_service_url = self.ENDPOINT + task + "?livedetection=true" bioID_service_headers = {"Authorization": "Bearer " + token} try: http_service_response = httpService.executeGet( http_client, bioID_service_url, bioID_service_headers) http_response = http_service_response.getHttpResponse() response_bytes = httpService.getResponseContent(http_response) response_string = httpService.convertEntityToString( response_bytes, Charset.forName("UTF-8")) json_response = JSONObject(response_string) httpService.consume(http_response) if json_response.get("Success") == True: return True else: print "BioID. Reason for failure : %s " % json_response.get( "Error") return False except: print "BioID. failed to invoke %s API: %s" % (task, sys.exc_info()[1]) return None finally: http_service_response.closeConnection()
def getState( self ): res = JSONObject() if self.last != None: res.put( "last", self.last.getTime() / 1000 ) if self.next != None: res.put( "next", self.next.getTime() / 1000 ) return res
def get_user_id_from_thumbsignin(self, request_parameters): transaction_id = ServerUtil.getFirstValue(request_parameters, TRANSACTION_ID) print "ThumbSignIn. Value of transaction_id is %s" % transaction_id get_user_request = "getUser/" + transaction_id print "ThumbSignIn. Value of get_user_request is %s" % get_user_request get_user_response = self.thumbsigninApiController.handleThumbSigninRequest(get_user_request, ts_api_key, ts_api_secret) print "ThumbSignIn. Value of get_user_response is %s" % get_user_response get_user_response_json = JSONObject(get_user_response) thumbsignin_user_id = get_user_response_json.get(USER_ID) print "ThumbSignIn. Value of thumbsignin_user_id is %s" % thumbsignin_user_id return thumbsignin_user_id
def __call__(self): # url地址 url = 'http://183.131.22.111/feeds/com.oppo.os.ads.show.feed.service.IFeedListRankSvc' # headers信息 headers = [NVPair("Content-Type", "application/json"), NVPair("Accept-Encoding", "gzip") ] # JSON格式的请求内容 imei = "86" + str(random.randint(1000000000000, 99999999999999)) submitdata = '{"methodName": "listFeedRank", "arguments": [{"parModuleId": "100", "posIds": "1", "networkId": "7", "openId": "sadlkalksjdasjd", "appVersion": "3.0.1", "clientTime": "", "contextTag": "[a,b,c],[e,f,g]", "location": "武汉", "pageStart": "0", "androidVersion": "4.4.4", "channel": "2", "category": "0", "dataType": "feed_show", "eventValue": "0", "imei": %s, "osVersion": "V2.1.0", "model": "X907", "moduleId": "8000", "sdkVersion": "", "ssoid": "11022", "romVersion": "000", "sessionId": "", "seqId": "", "systemId": "9", "clientIp": "222.248.000.000","carrier": "1","isDown": true,"down": 2,"up": 0}]}' % imei # URL请求 try: result = request1.POST(url, submitdata, headers) retcode = result.getStatusCode() flag = False if retcode == 200: message = result.getText() json = JSONObject(message) if json.has("data") == True: data = json.getJSONObject("data"); adlist = data.getJSONArray("adList"); for i in range(0, adlist.length()): adId = adlist.getJSONObject(i) value = adId.get("adId") if value==336: flag = True else: flag = False grinder.logger.info('imei1=' + imei) grinder.logger.info("result1=" + result.getText()) else: flag = False grinder.logger.info('imei2=' + imei) grinder.logger.info("result2=" + result.getText()) else: flag = False grinder.logger.info("statusCode3=" + str(retcode)) grinder.logger.info('imei3=' + imei) grinder.logger.info("result3=" + result.getText()) # 打印输出URL请求返回内容 # 返回结果检查,有返回特定字符,则判断请求成功 if flag == True: grinder.statistics.forLastTest.success = 1 else: grinder.statistics.forLastTest.success = 0 except TimeoutException, e: grinder.statistics.forLastTest.success = 0 grinder.logger.info("TimeoutException=" + str(e))
def fromMap(cls, obj): if isinstance(obj, dict): jsonObject = JSONObject() for k in obj: jsonObject.put(k, cls.fromMap(obj[k])) return jsonObject elif isinstance(obj, list): jsonArray = JSONArray() for k in obj: jsonArray.put(k) return jsonArray else: return obj
def dictToJsonObject(d): json = JSONObject() for key in d: value = d[key] if value is None: value = JSONObject.NULL elif isinstance(value, dict): value = dictToJsonObject(value) elif isinstance(value, list): value = listToJsonArray(value) json.put(key, value) return json
def tenant(): statusCode = [0L, 0L, 0L, 0L] result7 = HTTPRequest().GET('http://10.1.11.254/itsm/api/v2/ticket/getTicketList?filterType=all') code = result7.getStatusCode() data = result7.getText() json = JSONObject(data) grinder.logger.info(json.getString("errCode")) status = json.getString("errCode") if status == 'null': code = 300 if status != 'null': code = int(status) PTS.addHttpCode(code, statusCode) return statusCode
def update(self, dynamicScopeContext, configurationAttributes): # Get the client and SAML affilitation value authorizationGrant = dynamicScopeContext.getAuthorizationGrant() rpConfig = self.getRPConfig(authorizationGrant.getClient()) collectSpNameQualifier = rpConfig.get("collect") # if collectSpNameQualifier is not empty, we pass the affiliated SAML nameid if collectSpNameQualifier is not None: # then we look for the SAML persistentId value in user profile user = dynamicScopeContext.getUser() userPersistentIds = user.getAttributeValues("persistentId") if userPersistentIds is not None and userPersistentIds.size > 0: # go through existing user persistentIds for userPersistentId in userPersistentIds: # Format is : persistentIdSamlSpNQ|persistentIdIdp|persistentIdUid samlSpNameQualifier, samlIDPNameQualifier, samlSpNameIDSubject = tuple( userPersistentId.split("|")) # if the current RP already has a mapping then skip the second phase if samlSpNameQualifier == collectSpNameQualifier: # create a JSON object with the full NameID object samlNameIdJson = '{"SPNameQualifier":"%s","NameQualifier":"%s","value":"%s"}' % ( samlSpNameQualifier, samlIDPNameQualifier, samlSpNameIDSubject) samlNameId = JSONObject(samlNameIdJson) # Add the saml_nameid value to the result if present jsonWebResponse = dynamicScopeContext.getJsonWebResponse( ) claims = jsonWebResponse.getClaims() claims.setClaim("saml_nameid", samlNameId) return True
def parse_json(response): if response.startswith('['): json_arr = JSONArray(response) return [ json_arr.getJSONObject(i) for i in xrange(0, json_arr.length()) ] return JSONObject(response)
def tenant(): statusCode = [0L, 0L, 0L, 0L] headers = [NVPair('Content-Type', 'application/json'),NVPair('Accept', 'application/json'),NVPair('Origin', '10.1.11.254')] data = '{"message": {"toUserList": [5],"content": "同意"},"executor": {"957c8fa1cfda44b596ed3b4e29d6e27e": ["bdfe0b48fe7741b395dc599bdc80835e", "e10adc3949ba59abbe56e057f20f88dd"]},"form": {"title": "测试0010","urgentLevel": "5"}}' result7 = HTTPRequest().POST('http://10.1.11.254/itsm/api/v2/ticket/createTicket/5dbb00bb124c4d0e86f8cd0d15da0749', data, headers) code = result7.getStatusCode() data = result7.getText() json = JSONObject(data) grinder.logger.info(json.getString("errCode")) status = json.getString("errCode") if status == 'null': code = 300 if status != 'null': code = int(status) PTS.addHttpCode(code, statusCode) return statusCode
def initialize_thumbsignin(self, identity, request_path): # Invoking the authenticate/register ThumbSignIn API via the Java SDK thumbsignin_response = self.thumbsigninApiController.handleThumbSigninRequest( request_path, ts_api_key, ts_api_secret) print "ThumbSignIn. Value of thumbsignin_response is %s" % thumbsignin_response thumbsignin_response_json = JSONObject(thumbsignin_response) transaction_id = thumbsignin_response_json.get(TRANSACTION_ID) status_request_type = "authStatus" if request_path == AUTHENTICATE else "regStatus" status_request = status_request_type + "/" + transaction_id print "ThumbSignIn. Value of status_request is %s" % status_request authorization_header = self.thumbsigninApiController.getAuthorizationHeaderJsonStr( status_request, ts_api_key, ts_api_secret) print "ThumbSignIn. Value of authorization_header is %s" % authorization_header # {"authHeader":"HmacSHA256 Credential=X,SignedHeaders=accept;content-type;x-ts-date,Signature=X","XTsDate":"X"} authorization_header_json = JSONObject(authorization_header) auth_header = authorization_header_json.get("authHeader") x_ts_date = authorization_header_json.get("XTsDate") tsi_response_key = "authenticateResponseJsonStr" if request_path == AUTHENTICATE else "registerResponseJsonStr" identity.setWorkingParameter(tsi_response_key, thumbsignin_response) identity.setWorkingParameter("authorizationHeader", auth_header) identity.setWorkingParameter("xTsDate", x_ts_date) return None
def layerToJSON(layer): jsonlayer = JSONObject() jsonfeatures = JSONArray() ftype = layer.getFeatureStore().getDefaultFeatureType() geomAttributeName = ftype.getDefaultGeometryAttributeName() for f in layer.getFeatureStore().getFeatureSet(): jsonfeature = JSONObject() values = f.getValues() for k in values.keys(): value = values[k] if k == geomAttributeName: wkt = value.convertToWKT() jsonfeature.putOnce(k, wkt) else: jsonfeature.putOnce(k, value) jsonfeatures.put(jsonfeature) jsonlayer.put("features", jsonfeatures) return jsonlayer
def loads(s): if s.startswith('{'): objJson = JSONObject(s) python_json = jsonObjToDict(objJson) else: arrayjson = JSONArray(s) python_json = jsonArrayToDict(arrayjson) return python_json
def toJSON(self): jo = JSONObject() jo.put('hosts',JSONArray(self.DCHOSTS)) hm1 = HashMap() for (k,v) in self.SVCBYHOST.items(): hm1.put(k,v) jo.put('serviceByHost',JSONObject(hm1)) hm2 = HashMap() for (k,v) in self.HOSTBYSVC.items(): hm2.put(k,v) jo.put('hostByService',JSONObject(hm2)) return jo.toString()
def decode(self, buffer): try: if buffer == '': return buffer elif buffer[0] == '{': return JSONObject(buffer) elif buffer[0] == '[': return JSONArray(buffer) else: return buffer except JException, je: return buffer
def loadLayersGraphics(jsongraphicsstring): jsongraphics = JSONObject(jsongraphicsstring) if jsongraphics == None: return mapContextManager = MapContextLocator.getMapContextManager() store = loadLayerFromJSON(jsongraphics) layer = mapContextManager.createLayer(quickDrawingTool.DEFAULT_DRAW_LAYER, store) return layer
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 tenant(): statusCode = [0L, 0L, 0L, 0L] headers = [ NVPair('Content-Type', 'application/json'), NVPair('Accept', 'application/json'), NVPair('Origin', '10.1.11.254') ] data = '{"priority": ["5"],"source": ["alert"],"extParams": {}}' result7 = HTTPRequest().POST( 'http://10.1.11.254/itsm/api/v2/ticket/getAllTicket', data, headers) code = result7.getStatusCode() data = result7.getText() # grinder.logger.info(data) json = JSONObject(data) grinder.logger.info(json.getString("errCode")) status = json.getString("errCode") if status == 'null': code = 300 if status != 'null': code = int(status) PTS.addHttpCode(code, statusCode) return statusCode
def tenant(): statusCode = [0L, 0L, 0L, 0L] headers = [ NVPair('Content-Type', 'application/json'), NVPair('Accept', 'application/json'), NVPair('Origin', '10.1.11.254') ] data = '{"message":{"toUserList":[],"content":"同意"},"executor":{},"modelId":"a7ea82fdd36b4348b5e242af1531bfd3","form":{"title":"性能测试工单ffff","urgentLevel":"4","ticketDesc":"性能测试工单001","startTime":"2017-11-01T09:32:01.550Z","announcer":"性能测试工单001","inCategory":"0"},"ticketSource":"web"}' result7 = HTTPRequest().POST( 'http://10.1.11.254/itsm/api/v2/ticket/createTicket/a7ea82fdd36b4348b5e242af1531bfd3', data, headers) code = result7.getStatusCode() data = result7.getText() json = JSONObject(data) grinder.logger.info(json.getString("errCode")) status = json.getString("errCode") if status == 'null': code = 300 if status != 'null': code = int(status) PTS.addHttpCode(code, statusCode) return statusCode
def set_relying_party_login_url(identity): print "ThumbSignIn. Inside set_relying_party_login_url..." session_id = identity.getSessionId() session_attribute = session_id.getSessionAttributes() state_jwt_token = session_attribute.get("state") print "ThumbSignIn. Value of state_jwt_token is %s" % state_jwt_token relying_party_login_url = "" if (state_jwt_token is None) or ("." not in state_jwt_token): print "ThumbSignIn. Value of state parameter is not in the format of JWT Token" identity.setWorkingParameter(RELYING_PARTY_LOGIN_URL, relying_party_login_url) return None state_jwt_token_array = String(state_jwt_token).split("\\.") state_jwt_token_payload = state_jwt_token_array[1] state_payload_str = String(Base64Util.base64urldecode(state_jwt_token_payload), "UTF-8") state_payload_json = JSONObject(state_payload_str) print "ThumbSignIn. Value of state JWT token Payload is %s" % state_payload_json if state_payload_json.has("additional_claims"): additional_claims = state_payload_json.get("additional_claims") relying_party_id = additional_claims.get(RELYING_PARTY_ID) print "ThumbSignIn. Value of relying_party_id is %s" % relying_party_id identity.setWorkingParameter(RELYING_PARTY_ID, relying_party_id) if String(relying_party_id).startsWith("google.com"): # google.com/a/unphishableenterprise.com relying_party_id_array = String(relying_party_id).split("/") google_domain = relying_party_id_array[2] print "ThumbSignIn. Value of google_domain is %s" % google_domain relying_party_login_url = "https://www.google.com/accounts/AccountChooser?hd="+ google_domain + "%26continue=https://apps.google.com/user/hub" # elif (String(relying_party_id).startsWith("xyz")): # relying_party_login_url = "xyz.com" else: # If relying_party_login_url is empty, Gluu's default login URL will be used relying_party_login_url = "" print "ThumbSignIn. Value of relying_party_login_url is %s" % relying_party_login_url identity.setWorkingParameter(RELYING_PARTY_LOGIN_URL, relying_party_login_url) return None
def initialize_thumbsignin(self, identity, request_path): # Invoking the authenticate/register ThumbSignIn API via the Java SDK thumbsignin_response = self.thumbsigninApiController.handleThumbSigninRequest(request_path, ts_api_key, ts_api_secret) print "ThumbSignIn. Value of thumbsignin_response is %s" % thumbsignin_response thumbsignin_response_json = JSONObject(thumbsignin_response) transaction_id = thumbsignin_response_json.get(TRANSACTION_ID) status_request_type = "authStatus" if request_path == AUTHENTICATE else "regStatus" status_request = status_request_type + "/" + transaction_id print "ThumbSignIn. Value of status_request is %s" % status_request authorization_header = self.thumbsigninApiController.getAuthorizationHeaderJsonStr(status_request, ts_api_key, ts_api_secret) print "ThumbSignIn. Value of authorization_header is %s" % authorization_header # {"authHeader":"HmacSHA256 Credential=X,SignedHeaders=accept;content-type;x-ts-date,Signature=X","XTsDate":"X"} authorization_header_json = JSONObject(authorization_header) auth_header = authorization_header_json.get("authHeader") x_ts_date = authorization_header_json.get("XTsDate") tsi_response_key = "authenticateResponseJsonStr" if request_path == AUTHENTICATE else "registerResponseJsonStr" identity.setWorkingParameter(tsi_response_key, thumbsignin_response) identity.setWorkingParameter("authorizationHeader", auth_header) identity.setWorkingParameter("xTsDate", x_ts_date) return None
def toJSON(self): jo = JSONObject() jo.put('hosts',JSONArray(self.DCHOSTS)) self.addMapToJson( jo, "serviceByHost", self.SVCBYHOST ) self.addMapToJson( jo, "hostByService", self.HOSTBYSVC ) self.addMapToJson( jo, "addrMap", self.ADDRMAP ) self.addMapToJson( jo, "vips", self.VIPS ) jo.put('wfe_app_servers',JSONArray(self.WFE_APP_SERVERS)) return jo.toString()
def update(self, dynamicScopeContext, configurationAttributes): print "Dynamic scope [saml_nameid_scope]. Update method" # Get the client and SAML affilitation value authorizationGrant = dynamicScopeContext.getAuthorizationGrant() oidcClient = authorizationGrant.getClient() samlSpNameQualifier = oidcClient.getPolicyUri() # if samlSpNameQualifier is not empty, we pass the affiliated SAML nameid if (samlSpNameQualifier != None): # then we look for the SAML persistentId value in user profile print "Dynamic scope [saml_nameid_scope]. Found SPNameQualifier parameter '%s'" % samlSpNameQualifier user = dynamicScopeContext.getUser() userPersistentIds = user.getAttributeValues("persistentId") print "Dynamic scope [saml_nameid_scope]. Found SPNameQualifier parameter" if (userPersistentIds != None): if (userPersistentIds.size > 0): # go through existing user persistentIds for userPersistentId in userPersistentIds: # if the current RP already has a mapping then skip the second phase if (userPersistentId.find(samlSpNameQualifier) > -1): print "Dynamic scope [saml_nameid_scope]. Found matching persistentId '%s'" % userPersistentId # Format is : persistentIdSamlSpNQ|persistentIdIdp|persistentIdUid samlSpNameQualifier = StringHelper.split( userPersistentId, '|')[0] samlIDPNameQualifier = StringHelper.split( userPersistentId, '|')[1] samlSpNameIDSubject = StringHelper.split( userPersistentId, '|')[2] # create a JSON object with the full NameID object samlNameIdJson = '{"SPNameQualifier":"%s","NameQualifier":"%s","value":"%s"}' % ( samlSpNameQualifier, samlIDPNameQualifier, samlSpNameIDSubject) samlNameId = JSONObject(samlNameIdJson) # Add the saml_nameid value to the result if present jsonWebResponse = dynamicScopeContext.getJsonWebResponse( ) claims = jsonWebResponse.getClaims() claims.setClaim("saml_nameid", samlNameId) return True
def test(numMessages, islandId, domain, cloudDomain, stage1Mta): users = ["testuser1", "testuser2", "testuser3", "testuser4"] userMsgs = [0] * len(users) result = False mc = ManagementContainer.getInstance() cm = mc.getCustomerManager() cust = cloud.setupCustomer(mc, str(islandId), domain, True, False, users) try: cloud.propagateMtaConfig() office365Guid = cust.getGuids(CloudService.OFFICE365)[0].getGuid() # stage cloud messages for i in range(numMessages): if (i % 5) == 0: cloud.sendJournalMessage(office365Guid, users[0], ["invaliduser"], None, None, domain, cloudDomain, stage1Mta) userMsgs[0] += 1 elif (i % 4) == 0: cloud.sendJournalMessage(office365Guid, "invaliduser", [users[1]], None, None, domain, cloudDomain, stage1Mta) userMsgs[1] += 1 elif (i % 3) == 0: cloud.sendJournalMessage(office365Guid, "invaliduser", None, [users[2]], None, domain, cloudDomain, stage1Mta) userMsgs[2] += 1 elif (i % 2) == 0: cloud.sendJournalMessage(office365Guid, "invaliduser", None, None, [users[3]], domain, cloudDomain, stage1Mta) userMsgs[3] += 1 else : cloud.sendJournalMessage(office365Guid, users[0], [users[1]], [users[2]], [users[3]], domain, cloudDomain, stage1Mta) for j in range(len(users)): userMsgs[j] += 1 sleep(1) # wait for cloud messages to import msgs = cloud.findMessages(mc, cust.getCustID(), numMessages) if msgs.size() < numMessages: print 'Did not find all cloud messages in mailstore, only found', msgs.size() else: result = True # verify problematic character sets, e.g. windows-1252 if result is True: pm = mc.getPartitionManager() for msg in msgs: proxy = pm.getContentProxy(msg.getPartitionId()) reader = proxy.parseMessage(msg.getCustomerId(), -1, msg.getMessageId(), -1) json = JSONObject(JSONTokener(reader)) body = json.getString("data") encoding = None headers = json.getJSONArray("headers") for i in range(headers.length()): encoding = headers.getJSONObject(i).optString('Content-Type', encoding) if encoding == None: print 'missing Content-Type header for message ' + str(msg.getMessageId()) result = False break elif encoding.endswith('windows-1252'): print 'verifying windows-1252 encoding for message ' + str(msg.getMessageId()) if body != String('bullet \x95, euro sign \x80, latin F \x83, tilde \x98', 'windows-1252').toString(): print 'windows-1252 body content is incorrect for message ' + str(msg.getMessageId()) + ': ' + body result = False break elif encoding.endswith('utf-8'): print 'verifying utf-8 encoding for message ' + str(msg.getMessageId()) if body != 'bullet \xe2\x80\xa2, euro sign \xe2\x82\xac, latin F \xc6\x92, tilde \x7e': print 'utf-8 body content is incorrect for message ' + str(msg.getMessageId()) + ': ' + body result = False break else: print 'verifying ascii encoding for message ' + str(msg.getMessageId()) if body != 'plain ascii text...': print 'ascii body content is incorrect for message ' + str(msg.getMessageId()) + ': ' + body result = False break # verify individual users were categorized correctly as sender/recipients if result is True: print 'verifying categorized recipients...' for i in range(len(users)): userAddress = users[i] + '@' + domain userCount = 0; for msg in msgs: json = msg.getCategorizedRecipients() if json is None: print 'categorized recipients not set for: ' + msg.toString() result = False # count recipient fields for key in json.keys(): recipients = json.optJSONArray(key); for j in range(recipients.length()): if userAddress == recipients.getString(j): userCount += 1 # count sender field if userAddress == msg.getSender(): userCount += 1 if userMsgs[i] != userCount or result is False: print 'categorized recipients count for ' + userAddress + ' was ' + str(userCount) + ', but expected ' + str(userMsgs[i]) result = False break # verify archive search if result is True and not cloud.checkCustomerSearchStatus(mc, msgs, cust.getCustID()): print 'Did not find all cloud messages in index' result = False # verify individual users were resolved correctly if result is True: for i in range(len(users)): userAccount = mc.getUserManager().findUserForEmail(users[i] + '@' + domain) print 'searching for ' + str(userMsgs[i]) + ' indexed messages resolved to: ' + users[i] + '@' + domain + ', ' + str(userAccount.getUserID()) if not cloud.checkUserSearchStatus(mc, userMsgs[i], cust.getCustID(), userAccount.getUserID()): print 'Did not find messages in index for user: '******'@' + domain + ', ' + str(userAccount.getUserID()) result = False if result is True: print 'cloud message import successful' else: print 'cloud message import failed' finally: print "Deleting customer " + str(cust.getCustID()) + "..." cm.deleteCustomers([cust.getCustID()]) if result is True: sys.exit(0) else: sys.exit(1)
def prepareForStep(self, configurationAttributes, requestParameters, step): print "ThumbSignIn. Inside prepareForStep. Step %d" % step identity = CdiUtil.bean(Identity) authenticationService = CdiUtil.bean(AuthenticationService) global ts_host global ts_apiKey global ts_apiSecret global ts_statusPath identity.setWorkingParameter("ts_host", ts_host) identity.setWorkingParameter("ts_statusPath", ts_statusPath) self.setRelyingPartyLoginUrl(identity) thumbsigninApiController = ThumbsigninApiController() if (step == 1 or step == 3): print "ThumbSignIn. Prepare for step 1" # Invoking the authenticate ThumbSignIn API via the Java SDK authenticateResponseJsonStr = thumbsigninApiController.handleThumbSigninRequest( "authenticate", ts_apiKey, ts_apiSecret) print "ThumbSignIn. Value of authenticateResponseJsonStr is %s" % authenticateResponseJsonStr authenticateResponseJsonObj = JSONObject( authenticateResponseJsonStr) transactionId = authenticateResponseJsonObj.get("transactionId") authenticationStatusRequest = "authStatus/" + transactionId print "ThumbSignIn. Value of authenticationStatusRequest is %s" % authenticationStatusRequest authorizationHeaderJsonStr = thumbsigninApiController.getAuthorizationHeaderJsonStr( authenticationStatusRequest, ts_apiKey, ts_apiSecret) print "ThumbSignIn. Value of authorizationHeaderJsonStr is %s" % authorizationHeaderJsonStr # {"authHeader":"HmacSHA256 Credential=XXX, SignedHeaders=accept;content-type;x-ts-date, Signature=XXX","XTsDate":"XXX"} authorizationHeaderJsonObj = JSONObject(authorizationHeaderJsonStr) authorizationHeader = authorizationHeaderJsonObj.get("authHeader") xTsDate = authorizationHeaderJsonObj.get("XTsDate") print "ThumbSignIn. Value of authorizationHeader is %s" % authorizationHeader print "ThumbSignIn. Value of xTsDate is %s" % xTsDate identity.setWorkingParameter("authenticateResponseJsonStr", authenticateResponseJsonStr) identity.setWorkingParameter("authorizationHeader", authorizationHeader) identity.setWorkingParameter("xTsDate", xTsDate) return True elif (step == 2): print "ThumbSignIn. Prepare for step 2" if (identity.isSetWorkingParameter("userLoginFlow")): userLoginFlow = identity.getWorkingParameter("userLoginFlow") print "ThumbSignIn. Value of userLoginFlow is %s" % userLoginFlow user = authenticationService.getAuthenticatedUser() if (user == 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 == None): return False registerRequestPath = "register/" + user_name # Invoking the register ThumbSignIn API via the Java SDK registerResponseJsonStr = thumbsigninApiController.handleThumbSigninRequest( registerRequestPath, ts_apiKey, ts_apiSecret) print "ThumbSignIn. Value of registerResponseJsonStr is %s" % registerResponseJsonStr registerResponseJsonObj = JSONObject(registerResponseJsonStr) transactionId = registerResponseJsonObj.get("transactionId") registrationStatusRequest = "regStatus/" + transactionId print "ThumbSignIn. Value of registrationStatusRequest is %s" % registrationStatusRequest authorizationHeaderJsonStr = thumbsigninApiController.getAuthorizationHeaderJsonStr( registrationStatusRequest, ts_apiKey, ts_apiSecret) print "ThumbSignIn. Value of authorizationHeaderJsonStr is %s" % authorizationHeaderJsonStr # {"authHeader":"HmacSHA256 Credential=XXX, SignedHeaders=accept;content-type;x-ts-date, Signature=XXX","XTsDate":"XXX"} authorizationHeaderJsonObj = JSONObject(authorizationHeaderJsonStr) authorizationHeader = authorizationHeaderJsonObj.get("authHeader") xTsDate = authorizationHeaderJsonObj.get("XTsDate") print "ThumbSignIn. Value of authorizationHeader is %s" % authorizationHeader print "ThumbSignIn. Value of xTsDate is %s" % xTsDate identity.setWorkingParameter("userId", user_name) identity.setWorkingParameter("registerResponseJsonStr", registerResponseJsonStr) identity.setWorkingParameter("authorizationHeader", authorizationHeader) identity.setWorkingParameter("xTsDate", xTsDate) return True else: return False
print "\t-r\n\t\tRun all pending jobs." print "\t-l\n\t\tDump all jobs." print "\t-f FILENAME\n\t\tDefault: FILENAME=acroncfg.json" print "\t-s ID\n\t\tStart a job." print "\t-k ID\n\t\tStop a job." quit() config = loadjson( configfn ) tz = TimeZone.getDefault() if config.has( "tz" ): tz = TimeZone.getTimeZone( config.getString( "tz" ) ) statefn = config.getString( "statefile" ) if os.path.isfile( statefn ): states = loadjson( statefn ) else: states = JSONObject() jobsdesc = config.getJSONArray( "jobs" ) jobs = {} for i in range( jobsdesc.length() ): j = Job( jobsdesc.getJSONObject( i ), tz ) if states.has( j.id ): j.setState( states.getJSONObject( j.id ) ) jobs[j.id] = j for i in startlist: jobs[i].start() for i in stoplist: jobs[i].stop() if lst:
HttpResponse responseGet = client.execute(get); HttpEntity resEntityGet = responseGet.getEntity(); if (resEntityGet != null) { InputStream instream = resEntityGet.getContent(); BufferedReader str = new BufferedReader(new InputStreamReader( instream)); String ans = new String(""); build = new String(""); while ((ans = str.readLine()) != null) { build = build + ans; // Log.d( } JSONObject jobj = new JSONObject(build); JSONArray arr = jobj.getJSONArray("questions"); String arrlen = Integer.toString(arr.length()); // Log.d( for (int i = 0; i < arr.length(); i++) { JSONObject qs = arr.getJSONObject(i); qNum = qs.getString("nick");// nick &points question = qs.getString("points"); HashMap<String, String> hmap = new HashMap<String, String>(); hmap.put("nick", qNum); hmap.put("points", question); lmap.add(hmap); } String[] from = { "nick", "points" }; int[] to = { R.id.leader_tvnick, R.id.leader_tvpoints };
def authenticate(self, configurationAttributes, requestParameters, step): print "ThumbSignIn. Inside authenticate. Step %d" % step authenticationService = CdiUtil.bean(AuthenticationService) identity = CdiUtil.bean(Identity) global ts_host global ts_apiKey global ts_apiSecret global ts_statusPath identity.setWorkingParameter("ts_host", ts_host) identity.setWorkingParameter("ts_statusPath", ts_statusPath) thumbsigninApiController = ThumbsigninApiController() if (step == 1 or step == 3): print "ThumbSignIn. Authenticate for Step %d" % step login_flow = ServerUtil.getFirstValue(requestParameters, "login_flow") print "ThumbSignIn. Value of login_flow parameter is %s" % login_flow #Logic for ThumbSignIn Authentication Flow if (login_flow == "ThumbSignIn_Authentication" or login_flow == "ThumbSignIn_RegistrationSucess"): identity.setWorkingParameter("userLoginFlow", login_flow) print "ThumbSignIn. Value of userLoginFlow is %s" % identity.getWorkingParameter( "userLoginFlow") transactionId = ServerUtil.getFirstValue( requestParameters, "transactionId") print "ThumbSignIn. Value of transactionId is %s" % transactionId getUserRequest = "getUser/" + transactionId print "ThumbSignIn. Value of getUserRequest is %s" % getUserRequest getUserResponseJsonStr = thumbsigninApiController.handleThumbSigninRequest( getUserRequest, ts_apiKey, ts_apiSecret) print "ThumbSignIn. Value of getUserResponseJsonStr is %s" % getUserResponseJsonStr getUserResponseJsonObj = JSONObject(getUserResponseJsonStr) thumbSignIn_UserId = getUserResponseJsonObj.get("userId") print "ThumbSignIn. Value of thumbSignIn_UserId is %s" % thumbSignIn_UserId logged_in_status = authenticationService.authenticate( thumbSignIn_UserId) print "ThumbSignIn. logged_in status : %r" % (logged_in_status) return logged_in_status #Logic for ThumbSignIn Registration Flow identity.setWorkingParameter("userLoginFlow", "ThumbSignIn_Registration") print "ThumbSignIn. Value of userLoginFlow is %s" % identity.getWorkingParameter( "userLoginFlow") credentials = identity.getCredentials() user_name = credentials.getUsername() user_password = credentials.getPassword() print "ThumbSignIn. user_name: " + user_name #print "ThumbSignIn. user_password: "******"ThumbSignIn. Status of LDAP Authentication : %r" % ( logged_in) if (not logged_in): # Invoking the authenticate ThumbSignIn API via the Java SDK authenticateResponseJsonStr = thumbsigninApiController.handleThumbSigninRequest( "authenticate", ts_apiKey, ts_apiSecret) print "ThumbSignIn. Value of authenticateResponseJsonStr is %s" % authenticateResponseJsonStr authenticateResponseJsonObj = JSONObject( authenticateResponseJsonStr) transactionId = authenticateResponseJsonObj.get( "transactionId") authenticationStatusRequest = "authStatus/" + transactionId print "ThumbSignIn. Value of authenticationStatusRequest is %s" % authenticationStatusRequest authorizationHeaderJsonStr = thumbsigninApiController.getAuthorizationHeaderJsonStr( authenticationStatusRequest, ts_apiKey, ts_apiSecret) print "ThumbSignIn. Value of authorizationHeaderJsonStr is %s" % authorizationHeaderJsonStr # {"authHeader":"HmacSHA256 Credential=XXX, SignedHeaders=accept;content-type;x-ts-date, Signature=XXX","XTsDate":"XXX"} authorizationHeaderJsonObj = JSONObject( authorizationHeaderJsonStr) authorizationHeader = authorizationHeaderJsonObj.get( "authHeader") xTsDate = authorizationHeaderJsonObj.get("XTsDate") print "ThumbSignIn. Value of authorizationHeader is %s" % authorizationHeader print "ThumbSignIn. Value of xTsDate is %s" % xTsDate identity.setWorkingParameter("authenticateResponseJsonStr", authenticateResponseJsonStr) identity.setWorkingParameter("authorizationHeader", authorizationHeader) identity.setWorkingParameter("xTsDate", xTsDate) return False print "ThumbSignIn. Authenticate for step 1 successful" return True elif (step == 2): print "ThumbSignIn. Registration flow (step 2)" if (identity.isSetWorkingParameter("userLoginFlow")): userLoginFlow = identity.getWorkingParameter("userLoginFlow") print "ThumbSignIn. Value of userLoginFlow is %s" % userLoginFlow else: identity.setWorkingParameter("userLoginFlow", "ThumbSignIn_Registration") print "ThumbSignIn. Setting the value of userLoginFlow to %s" % identity.getWorkingParameter( "userLoginFlow") user = authenticationService.getAuthenticatedUser() if user == None: print "ThumbSignIn. Registration flow (step 2). Failed to determine user name" return False user_name = user.getUserId() print "ThumbSignIn. Registration flow (step 2). user_name: " + user_name print "ThumbSignIn. Registration flow (step 2) successful" return True else: return False
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
z = true; } else { z = z2; } if (!z) { Bundle bundle3 = new Bundle(); bundle3.putString(C0227d.f405o, "userLoginTask"); bundle3.putInt("errorCode", 16777216); bundle3.putString("errorDesc", "用户识别码错误"); mo8624g().mo8483a((C1526o) this, bundle3); mo8621d(C1527a.f4833c); return z2; } } mo8621d(C1527a.f4832b); JSONObject jSONObject = new JSONObject(); try { jSONObject.put("protocolVersion", 108); jSONObject.put("sequenceNo", mo8627j()); jSONObject.put("platformVersion", 1); jSONObject.put("peerID", mo8628k()); jSONObject.put("businessType", mo8624g().mo8500d()); jSONObject.put("clientVersion", mo8624g().mo8503e()); jSONObject.put("isCompressed", 0); jSONObject.put("cmdID", 1); jSONObject.put("userName", this.f4759b); byte[] encodeUseRSA = RsaEncode.encodeUseRSA(this.f4760c.getBytes(), m8747d(), m8748n()); jSONObject.put("passWord", new String(HextoChar.bytes_to_hex(encodeUseRSA, encodeUseRSA.length))); jSONObject.put("loginType", this.f4764g); jSONObject.put("sessionID", ""); jSONObject.put("verifyKey", this.f4762e);
def update(self, dynamicScopeContext, configurationAttributes): print "Dynamic scope [claims_scope]. Update method" # Get the client and session and dynamic claims authorizationGrant = dynamicScopeContext.getAuthorizationGrant() oidcClient = authorizationGrant.getClient() currentEntityId = "oidc:%s" % oidcClient.getClientName() # sessionDn = authorizationGrant.getSessionDn() # print "Dynamic scope [claims_scope]. Got session DN = '%s'" % sessionDn # sessionId = dynamicScopeContext.getEntryAttributeValue(sessionDn, "sessionId") # if ( sessionDn != None ): # prepare the search results attributes claimNamesJsonString = None claimsSrcJsonString = None # then we look for the SAML persistentId value in user profile user = dynamicScopeContext.getUser() userTransientIds = user.getAttributeValues("transientId") if ( userTransientIds != None ): if ( userTransientIds.size > 0 ): # save latest time (set to 0 initially) latestExpiryTimeSec = 0 # go through existing user persistentIds for userTransientId in userTransientIds: # if the current RP already has a mapping then skip the second phase transientIdRp = StringHelper.split(userTransientId,'|')[0] if ( transientIdRp == currentEntityId ): print "Dynamic scope [claims_scope]. Found matching transientId '%s'" % userTransientId # Format is : currentOidcRp, expiryTimeSec, userInfoUrl, accessToken expiryTimeSec = StringHelper.split(userTransientId,'|')[1] userInfoUrl = StringHelper.split(userTransientId,'|')[2] accessToken = StringHelper.split(userTransientId,'|')[3] # Check the last timestamp is newer than the current one and not older than 15 minutes (900 second) expiryTimeSec = StringHelper.toInteger(expiryTimeSec) currenttimeSec = int(round(time.time())) if ( expiryTimeSec > latestExpiryTimeSec and expiryTimeSec > (currenttimeSec - 900) ): # Save expiry and update/set the _claim_sources parameters latestExpiryTimeSec = expiryTimeSec # create a JSON object with _claim_sources for distributed claims claimsSrcJsonString = '{"src1":{"endpoint":"%s","access_token":"%s"}}' % ( userInfoUrl, accessToken ) # Set the _claim_names value to the result - static as per PCTF ####################################################### # "_claim_names": { # "given_name": "src1", # "family_name": "src1", # "birthdate": "src1", # "address": "src1" # }, # create a JSON object with _claim_sources for distributed claims claimNamesJsonString = '{"given_name":"src1","family_name":"src1","birthdate":"src1","address":"src1"}' # set the claims if they have been found if ( claimNamesJsonString != None and claimsSrcJsonString != None ): # Get the claims object jsonWebResponse = dynamicScopeContext.getJsonWebResponse() claims = jsonWebResponse.getClaims() # create JSON objects claimNamesJson = JSONObject(claimNamesJsonString) claimsSrcJson = JSONObject(claimsSrcJsonString) # set the claims claims.setClaim("_claim_names", claimNamesJson) claims.setClaim("_claim_sources", claimsSrcJson) return True
a = "https://login.mobile.reg2t.sandai.net:443"; } XLLog.m8433v(C1448a.this.f4591q, "send request use url = " + a + "#request=" + hashCode()); if (a.contains("login.mobile.reg2t.sandai.net")) { new Thread(new Runnable() { public final void run() { XLLog.m8433v(C1448a.this.f4591q, "login.mobile.reg2t.sandai.net -> ip address = " + XLUtilTools.getHostAddress("login.mobile.reg2t.sandai.net")); } }).start(); } C1465k.m8583a().mo8509k().post(C1448a.this.f4588n, a, null, this.f4597a, new BaseHttpClientListener() { public final void onSuccess(int i, Header[] headerArr, byte[] bArr) { String a = C1450a.this.m8540b(bArr); if (C1450a.this.f4598b == 1) { try { JSONObject jSONObject = new JSONObject(a); if (jSONObject.getInt("errorCode") != 8 || C1450a.this.f4599c >= 3) { C1450a.this.f4599c = 0; if (jSONObject.has("errorIsRetry") && jSONObject.getInt("errorIsRetry") != 0 && C1450a.this.f4600d < C1448a.this.mo8434a(C1450a.this.f4598b)) { C1450a.this.f4603g = (C1450a.this.f4603g + 1) % C1448a.this.mo8434a(C1450a.this.f4598b); C1450a.this.f4600d++; Bundle bundle = new Bundle(); bundle.putString("type", "onRetry"); bundle.putInt("count", C1450a.this.f4600d); bundle.putString("address", C1448a.this.mo8435a(C1450a.this.f4598b, C1450a.this.f4603g)); C1448a.this.mo8437a(bundle); C1450a.this.mo8446a(); } else if (C1450a.this.f4602f != null) { C1450a.m8538a(C1450a.this, a); C1450a.this.f4602f.mo8444a(a); }
def testObject(): import org.json.JSONObject json=new JSONObject() json.put("hello","world") print(json.toString())