Java Code Examples for org.wso2.carbon.context.PrivilegedCarbonContext#startTenantFlow()
The following examples show how to use
org.wso2.carbon.context.PrivilegedCarbonContext#startTenantFlow() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UserStoreActionListener.java From carbon-identity with Apache License 2.0 | 6 votes |
@Override public boolean doPreAddUser(String userName, Object credential, String[] roleList, Map<String, String> claims, String profile, UserStoreManager userStoreManager) throws UserStoreException { if (!isEnable() || isCalledViaIdentityMgtListners()) { return true; } try { AddUserWFRequestHandler addUserWFRequestHandler = new AddUserWFRequestHandler(); String domain = userStoreManager.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig .PROPERTY_DOMAIN_NAME); int tenantId = userStoreManager.getTenantId() ; String currentUser = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true); PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(currentUser); return addUserWFRequestHandler.startAddUserFlow(domain, userName, credential, roleList, claims, profile); } catch (WorkflowException e) { // Sending e.getMessage() since it is required to give error message to end user. throw new UserStoreException(e.getMessage(), e); } finally { PrivilegedCarbonContext.endTenantFlow(); } }
Example 2
Source File: GatewayUtils.java From carbon-apimgt with Apache License 2.0 | 6 votes |
/** * Get the config system registry for tenants * * @param tenantDomain - The tenant domain * @return - A UserRegistry instance for the tenant * @throws APIManagementException */ public static UserRegistry getRegistry(String tenantDomain) throws APIManagementException { PrivilegedCarbonContext.startTenantFlow(); if (tenantDomain != null && StringUtils.isNotEmpty(tenantDomain)) { PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); } else { PrivilegedCarbonContext.getThreadLocalCarbonContext() .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); } int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); UserRegistry registry; try { registry = RegistryServiceHolder.getInstance().getRegistryService().getConfigSystemRegistry(tenantId); } catch (RegistryException e) { String msg = "Failed to get registry instance for the tenant : " + tenantDomain + e.getMessage(); throw new APIManagementException(msg, e); } finally { PrivilegedCarbonContext.endTenantFlow(); } return registry; }
Example 3
Source File: RegistryBasedTaskRepository.java From carbon-commons with Apache License 2.0 | 6 votes |
@Override public synchronized boolean deleteTask(String taskName) throws TaskException { String tasksPath = this.getMyTasksPath(); String currentTaskPath = tasksPath + "/" + taskName; try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); if (!getRegistry().resourceExists(currentTaskPath)) { return false; } getRegistry().delete(currentTaskPath); return true; } catch (RegistryException e) { throw new TaskException("Error in deleting task '" + taskName + "' in the repository", Code.CONFIG_ERROR, e); } finally { PrivilegedCarbonContext.endTenantFlow(); } }
Example 4
Source File: DeviceTypeUtils.java From product-iots with Apache License 2.0 | 6 votes |
public static void setupMqttOutputAdapter() throws IOException { OutputEventAdapterConfiguration outputEventAdapterConfiguration = createMqttOutputEventAdapterConfiguration(DeviceTypeConstants.MQTT_ADAPTER_NAME, DeviceTypeConstants.MQTT_ADAPTER_TYPE, MessageType.TEXT); try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( DeviceTypeConstants.DEVICE_TYPE_PROVIDER_DOMAIN, true); DeviceTypeManagementDataHolder.getInstance().getOutputEventAdapterService() .create(outputEventAdapterConfiguration); } catch (OutputEventAdapterException e) { log.error("Unable to create Output Event Adapter : " + DeviceTypeConstants.MQTT_ADAPTER_NAME, e); } finally { PrivilegedCarbonContext.endTenantFlow(); } }
Example 5
Source File: RemoteTaskUtils.java From carbon-commons with Apache License 2.0 | 6 votes |
public static String createRemoteTaskMapping(int tenantId, String taskType, String taskName) throws TaskException { try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); Registry registry = RegistryBasedTaskRepository.getRegistry(); Resource res = registry.newResource(); res.setProperty(REMOTE_TASK_TENANT_ID, Integer.toString(tenantId)); res.setProperty(REMOTE_TASK_TASK_TYPE, taskType); res.setProperty(REMOTE_TASK_TASK_NAME, taskName); String remoteTaskId = generateRemoteTaskID(); registry.put(resourcePathFromRemoteTaskId(remoteTaskId), res); return remoteTaskId; } catch (Exception e) { throw new TaskException(e.getMessage(), Code.UNKNOWN, e); } finally { PrivilegedCarbonContext.endTenantFlow(); } }
Example 6
Source File: APIKeyMgtRemoteUserStoreMgtService.java From carbon-apimgt with Apache License 2.0 | 6 votes |
/** * Get the role list of a user. Works for any tenant domain. * @param username username with tenant domain * @return list of roles * @throws APIManagementException */ public String[] getUserRoles(String username) throws APIManagementException { String userRoles[] = null; String tenantDomain = MultitenantUtils.getTenantDomain(username); PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); UserStoreManager userStoreManager; try { userStoreManager = CarbonContext.getThreadLocalCarbonContext().getUserRealm().getUserStoreManager(); userRoles = userStoreManager.getRoleListOfUser(MultitenantUtils.getTenantAwareUsername(username)); } catch (UserStoreException e) { APIUtil.handleException("Error occurred retrieving roles of user " + username, e); } finally { PrivilegedCarbonContext.getThreadLocalCarbonContext().endTenantFlow(); } return userRoles; }
Example 7
Source File: RemoteTaskManager.java From carbon-commons with Apache License 2.0 | 6 votes |
@Override public void execute(ConfigurationContext ctx) throws ClusteringFault { try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(this.getTenantId(), true); TaskManager tm = TasksDSComponent.getTaskService().getTaskManager( this.getTaskType()); if (tm instanceof RemoteTaskManager) { this.result = new TaskStatusResult(); this.result.setRunning(((RemoteTaskManager) tm).isTaskRunning(this .getTaskName())); } } catch (Exception e) { throw new ClusteringFault(e.getMessage(), e); } finally { PrivilegedCarbonContext.endTenantFlow(); } }
Example 8
Source File: HostObjectUtils.java From carbon-apimgt with Apache License 2.0 | 6 votes |
/** * This method will clear recently added API cache. * @param username */ public static void invalidateRecentlyAddedAPICache(String username){ try{ PrivilegedCarbonContext.startTenantFlow(); APIManagerConfiguration config = HostObjectComponent.getAPIManagerConfiguration(); boolean isRecentlyAddedAPICacheEnabled = Boolean.parseBoolean(config.getFirstProperty(APIConstants.API_STORE_RECENTLY_ADDED_API_CACHE_ENABLE)); if (username != null && isRecentlyAddedAPICacheEnabled) { String tenantDomainFromUserName = MultitenantUtils.getTenantDomain(username); if (tenantDomainFromUserName != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomainFromUserName)) { PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomainFromUserName, true); } else { PrivilegedCarbonContext.getThreadLocalCarbonContext() .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); } Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache("RECENTLY_ADDED_API") .remove(username + ":" + tenantDomainFromUserName); } } finally { PrivilegedCarbonContext.endTenantFlow(); } }
Example 9
Source File: UserStoreActionListener.java From carbon-identity with Apache License 2.0 | 6 votes |
@Override public boolean doPreDeleteUserClaimValues(String userName, String[] claims, String profileName, UserStoreManager userStoreManager) throws UserStoreException { if (!isEnable() || isCalledViaIdentityMgtListners()) { return true; } try { DeleteMultipleClaimsWFRequestHandler deleteMultipleClaimsWFRequestHandler = new DeleteMultipleClaimsWFRequestHandler(); String domain = userStoreManager.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig .PROPERTY_DOMAIN_NAME); int tenantId = userStoreManager.getTenantId() ; String currentUser = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true); PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(currentUser); return deleteMultipleClaimsWFRequestHandler.startDeleteMultipleClaimsWorkflow(domain, userName, claims, profileName); } catch (WorkflowException e) { // Sending e.getMessage() since it is required to give error message to end user. throw new UserStoreException(e.getMessage(), e); } finally { PrivilegedCarbonContext.endTenantFlow(); } }
Example 10
Source File: UserStoreActionListener.java From carbon-identity with Apache License 2.0 | 6 votes |
@Override public boolean doPreDeleteRole(String roleName, UserStoreManager userStoreManager) throws UserStoreException { if (!isEnable() || isCalledViaIdentityMgtListners()) { return true; } try { DeleteRoleWFRequestHandler deleteRoleWFRequestHandler = new DeleteRoleWFRequestHandler(); String domain = userStoreManager.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig .PROPERTY_DOMAIN_NAME); int tenantId = userStoreManager.getTenantId() ; String currentUser = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true); PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(currentUser); return deleteRoleWFRequestHandler.startDeleteRoleFlow(domain, roleName); } catch (WorkflowException e) { // Sending e.getMessage() since it is required to give error message to end user. throw new UserStoreException(e.getMessage(), e); } finally { PrivilegedCarbonContext.endTenantFlow(); } }
Example 11
Source File: RegistryBasedTaskRepository.java From carbon-commons with Apache License 2.0 | 6 votes |
private TaskInfo getTaskInfoRegistryPath(String path) throws Exception { try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); Resource resource = getRegistry().get(path); InputStream in = resource.getContentStream(); TaskInfo taskInfo; /* * the following synchronized block is to avoid * "org.xml.sax.SAXException: FWK005" error where the XML parser is * not thread safe */ synchronized (getTaskUnmarshaller()) { taskInfo = (TaskInfo) getTaskUnmarshaller().unmarshal(in); } in.close(); taskInfo.getProperties().put(TaskInfo.TENANT_ID_PROP, String.valueOf(this.getTenantId())); return taskInfo; } finally { PrivilegedCarbonContext.endTenantFlow(); } }
Example 12
Source File: APIGatewayManager.java From carbon-apimgt with Apache License 2.0 | 5 votes |
/** * Get the specified in/out sequences from api object * * @param api -API object * @param tenantDomain * @throws APIManagementException */ private void setCustomSequencesToBeAdded(API api, String tenantDomain, GatewayAPIDTO gatewayAPIDTO) throws APIManagementException { if (APIUtil.isSequenceDefined(api.getInSequence()) || APIUtil.isSequenceDefined(api.getOutSequence())) { try { PrivilegedCarbonContext.startTenantFlow(); if (tenantDomain != null && !"".equals(tenantDomain)) { PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); } else { PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); } int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); if (APIUtil.isSequenceDefined(api.getInSequence())) { addSequence(api, tenantId, gatewayAPIDTO, APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN, APIConstants.API_CUSTOM_SEQ_IN_EXT, api.getInSequence()); } if (APIUtil.isSequenceDefined(api.getOutSequence())) { addSequence(api, tenantId, gatewayAPIDTO, APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT, APIConstants.API_CUSTOM_SEQ_OUT_EXT, api.getOutSequence()); } } catch (Exception e) { String msg = "Error in deploying the sequence to gateway"; log.error(msg, e); throw new APIManagementException(msg); } finally { PrivilegedCarbonContext.endTenantFlow(); } } }
Example 13
Source File: EventPublisherServiceTest.java From carbon-device-mgt with Apache License 2.0 | 5 votes |
private void publishAsTenant(Object[] metaData) throws DataPublisherConfigurationException { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(TENANT_DOMAIN, true); try { boolean published = this.eventsPublisherService.publishEvent(STREAM_NAME, "1.0.0", metaData, getEventProps(), getEventProps()); Assert.assertTrue(published); } finally { PrivilegedCarbonContext.endTenantFlow(); } }
Example 14
Source File: ServerStartupListener.java From carbon-apimgt with Apache License 2.0 | 5 votes |
/** * Method to create a tenant upon initial server startup */ public static void initializeTenant(String username) throws Exception { TenantInfoBean tenantInfoBean = new TenantInfoBean(); TenantMgtAdminService tenantMgtAdminService = new TenantMgtAdminService(); char[] password = MicroGatewayCommonUtil.getRandomString(20).toCharArray(); String tenantDomain = MultitenantUtils.getTenantDomain(username); if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username); if (CommonUtil.isDomainNameAvailable(tenantDomain)) { tenantInfoBean.setActive(true); tenantInfoBean.setAdmin(tenantAwareUsername); tenantInfoBean.setAdminPassword(password.toString()); tenantInfoBean.setFirstname(TenantInitializationConstants.DEFAULT_FIRST_NAME); tenantInfoBean.setLastname(TenantInitializationConstants.DEFAULT_LAST_NAME); tenantInfoBean.setTenantDomain(tenantDomain); tenantInfoBean.setEmail(TenantInitializationConstants.DEFAULT_EMAIL); try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext() .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID); tenantMgtAdminService.addTenant(tenantInfoBean); tenantMgtAdminService.activateTenant(tenantDomain); } finally { PrivilegedCarbonContext.endTenantFlow(); } MicroGatewayCommonUtil.cleanPasswordCharArray(password); log.info("Successfully initialized tenant with tenant domain: " + tenantDomain); } else { log.info("Tenant with tenant domain " + tenantDomain + " already exists."); } } else { if (log.isDebugEnabled()) { log.debug("Skipping initializing super tenant space since execution is currently in super tenant flow."); } } }
Example 15
Source File: AbstractAPIManager.java From carbon-apimgt with Apache License 2.0 | 4 votes |
protected void startTenantFlow(String tenantDomain) { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); }
Example 16
Source File: InMemoryIdentityDataStore.java From carbon-identity-framework with Apache License 2.0 | 4 votes |
@Override public UserIdentityClaimsDO load(String userName, UserStoreManager userStoreManager) { try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID); Cache<String, UserIdentityClaimsDO> cache = getCache(); if (userName != null && cache != null) { if (userStoreManager instanceof org.wso2.carbon.user.core.UserStoreManager) { if (!IdentityUtil.isUserStoreCaseSensitive((org.wso2.carbon.user.core.UserStoreManager) userStoreManager)) { if (log.isDebugEnabled()) { log.debug("Case insensitive user store found. Changing username from : " + userName + " to : " + userName.toLowerCase()); } userName = userName.toLowerCase(); } } org.wso2.carbon.user.core.UserStoreManager store = (org.wso2.carbon.user.core.UserStoreManager) userStoreManager; String domainName = store.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME); UserIdentityClaimsDO userIdentityDTO = (UserIdentityClaimsDO) cache.get(domainName + userStoreManager .getTenantId() + userName); if (userIdentityDTO != null && log.isDebugEnabled()) { StringBuilder data = new StringBuilder("{"); if (userIdentityDTO.getUserIdentityDataMap() != null) { for (Map.Entry<String, String> entry : userIdentityDTO.getUserIdentityDataMap().entrySet()) { data.append("[" + entry.getKey() + " = " + entry.getValue() + "], "); } } if (data.indexOf(",") >= 0) { data.deleteCharAt(data.lastIndexOf(",")); } data.append("}"); log.debug("Loaded UserIdentityClaimsDO from cache for user :" + userName + " with claims: " + data); } return userIdentityDTO; } } catch (UserStoreException e) { log.error("Error while obtaining tenant ID from user store manager"); } finally { PrivilegedCarbonContext.endTenantFlow(); } return null; }
Example 17
Source File: RemoteTaskCallbackServlet.java From carbon-commons with Apache License 2.0 | 4 votes |
@Override protected void doPost(HttpServletRequest req, HttpServletResponse res) { String taskType = null, taskName; try { String remoteTaskId = req.getHeader(REMOTE_SYSTEM_TASK_HEADER_ID); if (remoteTaskId == null) { return; } /* if task execution node is not fully started yet, ignore this remote trigger */ if (!TasksDSComponent.getTaskService().isServerInit()) { if (log.isDebugEnabled()) { log.debug("Ignoring remote task triggered before server startup: " + remoteTaskId); } return; } if (log.isDebugEnabled()) { log.debug("Remote Task Request Received: " + remoteTaskId); } Object[] taskInfo = RemoteTaskUtils.lookupRemoteTask(remoteTaskId); int tenantId = (Integer) taskInfo[0]; taskType = (String) taskInfo[1]; taskName = (String) taskInfo[2]; try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true); TaskManager tm = TasksDSComponent.getTaskService().getTaskManager(taskType); if (!(tm instanceof RemoteTaskManager)) { log.error("The server is not running in remote task mode, " + "the current task manager type used is '" + tm.getClass() + "'"); return; } ((RemoteTaskManager) tm).runTask(taskName); } finally { PrivilegedCarbonContext.endTenantFlow(); } } catch (TaskException e) { if (e.getCode().equals(Code.TASK_NODE_NOT_AVAILABLE)) { log.debug("Remote task request dispatched to an unsupported task node with task type: " + taskType + " returning a SC_NOT_FOUND error code"); /* this is so, a load balancer will send the request to a different task node */ res.setStatus(HttpServletResponse.SC_NOT_FOUND); } else { log.error("Error in executing remote task request: " + e.getMessage(), e); } } }
Example 18
Source File: DeviceManagementAdminServiceImpl.java From carbon-device-mgt with Apache License 2.0 | 4 votes |
@Override @GET public Response getDevicesByName(@QueryParam("name") @Size(max = 45) String name, @QueryParam("type") @Size(min = 2, max = 45) String type, @QueryParam("tenant-domain") String tenantDomain, @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("offset") int offset, @QueryParam("limit") int limit) { RequestValidationUtil.validatePaginationParameters(offset, limit); int currentTenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); if (MultitenantConstants.SUPER_TENANT_ID != currentTenantId) { return Response.status(Response.Status.UNAUTHORIZED).entity( new ErrorResponse.ErrorResponseBuilder().setMessage( "Current logged in user is not authorized to perform this operation").build()).build(); } try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(DeviceMgtAPIUtils.getTenantId(tenantDomain)); PaginationRequest request = new PaginationRequest(offset, limit); request.setDeviceType(type); request.setDeviceName(name); List<Device> devices = DeviceMgtAPIUtils.getDeviceManagementService(). getDevicesByNameAndType(request, false); // setting up paginated result DeviceList deviceList = new DeviceList(); deviceList.setList(devices); deviceList.setCount(devices.size()); return Response.status(Response.Status.OK).entity(deviceList).build(); } catch (DeviceManagementException e) { String msg = "Error occurred at server side while fetching device list."; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } finally { PrivilegedCarbonContext.endTenantFlow(); } }
Example 19
Source File: JWTValidator.java From carbon-apimgt with Apache License 2.0 | 4 votes |
private JWTValidationInfo getJwtValidationInfo(SignedJWT jwtToken, String cacheKey) throws APISecurityException { String jwtHeader = jwtToken.getHeader().toString(); String tenantDomain = GatewayUtils.getTenantDomain(); String tokenSignature = jwtToken.getSignature().toString(); JWTValidationInfo jwtValidationInfo = null; if (isGatewayTokenCacheEnabled) { String cacheToken = (String) getGatewayTokenCache().get(tokenSignature); if (cacheToken != null) { if (getGatewayKeyCache().get(cacheKey) != null) { JWTValidationInfo tempJWTValidationInfo = (JWTValidationInfo) getGatewayKeyCache().get(cacheKey); String rawPayload = tempJWTValidationInfo.getRawPayload(); if (rawPayload.equals(jwtToken.getParsedString())) { checkTokenExpiration(tokenSignature, tempJWTValidationInfo, tenantDomain); jwtValidationInfo = tempJWTValidationInfo; } } } else if (getInvalidTokenCache().get(tokenSignature) != null) { if (log.isDebugEnabled()) { log.debug("Token retrieved from the invalid token cache. Token: " + GatewayUtils .getMaskedToken(jwtHeader)); } log.error("Invalid JWT token. " + GatewayUtils.getMaskedToken(jwtHeader)); jwtValidationInfo = new JWTValidationInfo(); jwtValidationInfo.setValidationCode(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS); jwtValidationInfo.setValid(false); } } if (jwtValidationInfo == null) { try { jwtValidationInfo = jwtValidationService.validateJWTToken(jwtToken); if (isGatewayTokenCacheEnabled) { // Add token to tenant token cache if (jwtValidationInfo.isValid()) { getGatewayTokenCache().put(tokenSignature, tenantDomain); getGatewayKeyCache().put(cacheKey, jwtValidationInfo); } else { getInvalidTokenCache().put(tokenSignature, tenantDomain); } if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { //Add the tenant domain as a reference to the super tenant cache so we know from which tenant // cache //to remove the entry when the need occurs to clear this particular cache entry. try { // Start super tenant flow PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext() .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); // Add token to super tenant token cache if (jwtValidationInfo.isValid()) { getGatewayTokenCache().put(tokenSignature, tenantDomain); } else { getInvalidTokenCache().put(tokenSignature, tenantDomain); } } finally { PrivilegedCarbonContext.endTenantFlow(); } } } return jwtValidationInfo; } catch (APIManagementException e) { throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE); } } return jwtValidationInfo; }
Example 20
Source File: APIKeyValidatorTestCase.java From carbon-apimgt with Apache License 2.0 | 4 votes |
@Test public void testCheckForRevokedTokenWhereAlreadyGetCached() throws APISecurityException { try { String tenantDomain = "carbon.super"; PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext() .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID); PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername("admin"); APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO(); apiKeyValidationInfoDTO.setAuthorized(true); PowerMockito.when(APIUtil.isAccessTokenExpired(apiKeyValidationInfoDTO)).thenReturn(true); AxisConfiguration axisConfiguration = Mockito.mock(AxisConfiguration.class); Cache tokenCache = Mockito.mock(Cache.class); Cache keyCache = Mockito.mock(Cache.class); Cache resourceCache = Mockito.mock(Cache.class); Cache invalidTokenCache = Mockito.mock(Cache.class); APIKeyDataStore apiKeyDataStore = Mockito.mock(APIKeyDataStore.class); APIKeyValidator apiKeyValidator = getAPIKeyValidator(axisConfiguration, invalidTokenCache, tokenCache, keyCache, resourceCache, apiKeyDataStore, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); apiKeyValidator.dataStore = apiKeyDataStore; Mockito.when(tokenCache.get(Mockito.anyString())).thenReturn(null); Mockito.when(invalidTokenCache.get(Mockito.anyString())).thenReturn("carbon.super"); Mockito.when(keyCache.get(Mockito.anyString())).thenReturn(apiKeyValidationInfoDTO); Mockito.when(apiKeyDataStore.getAPIKeyData(context, apiVersion, apiKey, authenticationScheme, clientDomain, matchingResource, httpVerb, tenantDomain,new ArrayList<>())).thenReturn(apiKeyValidationInfoDTO); apiKeyValidator.getKeyValidationInfo(context, apiKey, apiVersion, authenticationScheme, clientDomain, matchingResource, httpVerb, defaultVersionInvoked,new ArrayList<>()); Mockito.verify(tokenCache, Mockito.times(1)).get(Mockito.anyString()); Mockito.verify(invalidTokenCache, Mockito.times(1)).get(Mockito.anyString()); Mockito.verify(keyCache, Mockito.times(0)).get(Mockito.anyString()); Mockito.verify(tokenCache, Mockito.times(0)).put(Mockito.anyString(), Mockito.anyString()); Mockito.verify(keyCache, Mockito.times(0)).put(Mockito.any(APIKeyValidationInfoDTO.class), Mockito .anyString()); Mockito.verify(invalidTokenCache, Mockito.times(0)).put(Mockito.anyString(), Mockito.anyString()); Mockito.verify(tokenCache, Mockito.times(0)).remove(Mockito.anyString()); Mockito.verify(invalidTokenCache, Mockito.times(0)).remove(Mockito.anyString()); Mockito.verify(keyCache, Mockito.times(0)).remove(Mockito.anyString()); Mockito.verify(apiKeyDataStore, Mockito.times(0)).getAPIKeyData(context, apiVersion, apiKey, authenticationScheme, clientDomain, matchingResource, httpVerb, tenantDomain,new ArrayList<>()); } finally { PrivilegedCarbonContext.endTenantFlow(); } }